private static void DownloadAttachment(HttpContext context, AttachmentInfo attachmentInfo)
		{
			context.Response.Clear();

			context.Response.ContentType = "application/octet-stream";
			context.Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + attachmentInfo.OriginalFileName + "\"");

			var fileService = ServiceManager.GetService<FileService>();
			long fileSize = fileService.GetFileSize(attachmentInfo.UniqueFileName);
			long receivedBytes = 0;
			const int chunkSize = 100*1024;

			while (receivedBytes < fileSize)
			{
				byte[] buffer = fileService.DownloadChunk(attachmentInfo.UniqueFileName, receivedBytes, chunkSize);
				context.Response.BinaryWrite(buffer);
				receivedBytes += buffer.Length;
			}

			context.Response.End();
		}
    /// <summary>
    /// Checks whether the name is unique.
    /// </summary>
    private bool IsAttachmentNameUnique(AttachmentInfo ai, string name)
    {
        if (ai != null)
        {
            // Check that the name is unique in the document or version context
            Guid attachmentFormGuid = QueryHelper.GetGuid("formguid", Guid.Empty);
            bool nameIsUnique = false;
            if (attachmentFormGuid == Guid.Empty)
            {
                // Get the node
                nameIsUnique = DocumentHelper.IsUniqueAttachmentName(Node, name, ai.AttachmentExtension, ai.AttachmentID, TreeProvider);
            }
            else
            {
                nameIsUnique = AttachmentInfoProvider.IsUniqueTemporaryAttachmentName(attachmentFormGuid, name, ai.AttachmentExtension, ai.AttachmentID);
            }

            return nameIsUnique;
        }

        return false;
    }
    public override void ReloadData(bool forceReload)
    {
        Visible = !StopProcessing;
        if (StopProcessing)
        {
            dsAttachments.StopProcessing = true;
            newAttachmentElem.StopProcessing = true;
            // Do nothing
        }
        else
        {
            if (Node != null)
            {
                dsAttachments.Path = Node.NodeAliasPath;
                dsAttachments.CultureCode = Node.DocumentCulture;

                SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID);
                SiteName = si.SiteName;
            }

            // For new culture version temporary attachments are always used
            if ((Form != null) && (Form.Mode == FormModeEnum.InsertNewCultureVersion) && ((LastAction == "update") || (LastAction == "insert")))
            {
                dsAttachments.DocumentVersionHistoryID = 0;
                SiteName = null;
            }

            // Ensure correct site name
            dsAttachments.SiteName = SiteName;

            // Get attachment GUID
            attachmentGuid = ValidationHelper.GetGuid(Value, Guid.Empty);
            if (attachmentGuid == Guid.Empty)
            {
                dsAttachments.StopProcessing = true;
            }

            if ((Node == null) || UsesWorkflow)
            {
                dsAttachments.DocumentVersionHistoryID = VersionHistoryID;
            }
            dsAttachments.AttachmentFormGUID = FormGUID;
            dsAttachments.AttachmentGUID = attachmentGuid;

            // Force reload datasource
            if (forceReload)
            {
                dsAttachments.DataSource = null;
                dsAttachments.DataBind();
            }

            // Ensure right column name (for attachments under workflow)
            if (!DataHelper.DataSourceIsEmpty(dsAttachments.DataSource))
            {
                DataSet ds = (DataSet)dsAttachments.DataSource;
                if (ds != null)
                {
                    DataTable dt = (ds).Tables[0];
                    if (!dt.Columns.Contains("AttachmentFormGUID"))
                    {
                        dt.Columns.Add("AttachmentFormGUID");
                    }

                    // Get inner attachment
                    innerAttachment = new AttachmentInfo(dt.Rows[0]);
                    Value = innerAttachment.AttachmentGUID;
                    hdnAttachName.Value = innerAttachment.AttachmentName;

                    // Check if temporary attachment should be created
                    createTempAttachment = ((DocumentID == 0) && (DocumentID != innerAttachment.AttachmentDocumentID));
                }
            }

            // Initialize button for adding attachments
            newAttachmentElem.ImageUrl = ResolveUrl(GetImageUrl("Design/Controls/DirectUploader/upload_new.png"));
            newAttachmentElem.ImageWidth = 16;
            newAttachmentElem.ImageHeight = 16;
            newAttachmentElem.SourceType = MediaSourceEnum.Attachment;
            newAttachmentElem.DocumentID = DocumentID;
            newAttachmentElem.NodeParentNodeID = NodeParentNodeID;
            newAttachmentElem.NodeClassName = NodeClassName;
            newAttachmentElem.ResizeToWidth = ResizeToWidth;
            newAttachmentElem.ResizeToHeight = ResizeToHeight;
            newAttachmentElem.ResizeToMaxSideSize = ResizeToMaxSideSize;
            newAttachmentElem.FormGUID = FormGUID;
            newAttachmentElem.AttachmentGUIDColumnName = GUIDColumnName;
            newAttachmentElem.AllowedExtensions = AllowedExtensions;
            newAttachmentElem.ParentElemID = ClientID;
            newAttachmentElem.ForceLoad = true;
            newAttachmentElem.InnerDivHtml = GetString("attach.uploadfile");
            newAttachmentElem.InnerDivClass = InnerDivClass;
            newAttachmentElem.InnerLoadingDivHtml = GetString("attach.loading");
            newAttachmentElem.InnerLoadingDivClass = InnerLoadingDivClass;
            newAttachmentElem.IsLiveSite = IsLiveSite;
            newAttachmentElem.IncludeNewItemInfo = true;
            newAttachmentElem.CheckPermissions = CheckPermissions;
            newAttachmentElem.NodeSiteName = SiteName;

            imgDisabled.ImageUrl = ResolveUrl(GetImageUrl("Design/Controls/DirectUploader/upload_newdisabled.png"));

            // Bind UniGrid to DataSource
            gridAttachments.DataSource = dsAttachments.DataSource;
            gridAttachments.LoadGridDefinition();
            gridAttachments.ReloadData();
        }
    }
    /// <summary>
    /// Moves an unsorted attachment up in the list. Called when the "Move attachment up" button is pressed.
    /// Expects the "Create example document" and "Insert unsorted attachment" methods to be run first.
    /// </summary>
    private bool MoveAttachmentUp()
    {
        // Create a new instance of the Tree provider
        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

        // Get the example document
        TreeNode node = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/API-Example", "en-us");

        if (node != null)
        {
            string where = "AttachmentIsUnsorted = 1";
            string orderBy = "AttachmentLastModified DESC";

            // Get the document's unsorted attachments with the latest on top
            DataSet attachments = DocumentHelper.GetAttachments(node, where, orderBy, false, tree);

            if (!DataHelper.DataSourceIsEmpty(attachments))
            {
                // Create attachment info object from the first DataRow
                AttachmentInfo attachment = new AttachmentInfo(attachments.Tables[0].Rows[0]);

                // Move the attachment
                DocumentHelper.MoveAttachmentUp(attachment.AttachmentGUID, node);

                return true;
            }
            else
            {
                apiMoveAttachmentDown.ErrorMessage = "No attachments were found.";
            }
        }

        return false;
    }
    /// <summary>
    /// Selects the given attachment as current item
    /// </summary>
    /// <param name="callSelection">If true, the action to select media item should be raised</param>
    /// <param name="attachment"></param>
    protected void SelectAttachment(bool callSelection, AttachmentInfo attachment)
    {
        string fileName = Path.GetFileNameWithoutExtension(attachment.AttachmentName);

        if (callSelection)
        {
            SelectMediaItem(
                fileName,
                attachment.AttachmentExtension,
                attachment.AttachmentImageWidth,
                attachment.AttachmentImageHeight,
                attachment.AttachmentSize,
                attachment.AttachmentUrl
                );
        }

        if (SourceType == MediaSourceEnum.DocumentAttachments)
        {
            ItemToColorize = attachment.AttachmentGUID;
        }
        else if (attachment.AttachmentDocumentID == TreeNodeObj.DocumentID)
        {
            ItemToColorize = TreeNodeObj.NodeGUID;
        }
    }
        private void BindArticle(int articleId)
        {
            lblInvalidCategory.Visible = false;
            ArticleInfo objArticle = ArticleController.Get(articleId);
            if (objArticle == null)
            {
                return;
            }

            txtTitle.Text = objArticle.Title;
            txtAuthor.Text = objArticle.Author;
            chkPublish.Checked = objArticle.Authed;
			txtKeywords.Text = objArticle.Keywords;
			txtImage.Text=objArticle.Image;
            /*
            txtSource.Text = objArticle.Source;
            chkQuote.Checked = objArticle.Quote;
            txtPinOrder.Text = Convert.ToString(objArticle.PinOrder);
            chkDraft.Checked = objArticle.Draft;

            ctlLinkUrl.Url = objArticle.LinkUrl;
            chkFeatured.Checked = objArticle.Featured;
            chkAuthed.Checked = objArticle.Authed;
            chkActive.Checked = objArticle.Active;
            */
            //ctlImage.Url = objArticle.Image;

            //foreach (ListItem l in drpThumbnailImage.Items) { Response.Write(l.Text + "<br>"); }
			
            /*if (objArticle.Image != "")
            {
                foreach (ListItem m in drpThumbnailImage.Items)
                {
                    if (m.Text == objArticle.Image.Remove(0, objArticle.Image.LastIndexOf("/") + 1))
                    {
                        drpThumbnailImage.SelectedValue = drpThumbnailImage.Items.FindByText(objArticle.Image.Remove(0, objArticle.Image.LastIndexOf("/") + 1)).Value;
                        break;
                    }
                }
            }*/
			/*
            if (objArticle.TopStoriesImage != "")
            {
                foreach (ListItem m in drpTopStoriesPosition.Items)
                {
                    if (m.Text == objArticle.TopStoriesImage.Remove(0, objArticle.TopStoriesImage.LastIndexOf("/") + 1))
                    {
                        drpTopStoriesPosition.SelectedValue = drpTopStoriesPosition.Items.FindByText(objArticle.TopStoriesImage.Remove(0, objArticle.TopStoriesImage.LastIndexOf("/") + 1)).Value;
                        break;
                    }
                }
            }
			*/
            if (!Null.IsNull(objArticle.PublishDate.ToString()))
            {
                string time = Convert.ToDateTime(objArticle.PublishDate).ToString("hh:mm:tt");
				string[] splitTime = time.Split(':');
                // Response.Write("Welcome");
                // Response.Write(time.Substring(0, 2) + " " + time.Substring(3, 2) + " " + time.Substring(6, 2) + " " + objArticle.Id);

                PublishHour.SelectedIndex = PublishHour.Items.IndexOf(PublishHour.Items.FindByText(splitTime[0]));
				PublishMinute.SelectedIndex = PublishMinute.Items.IndexOf(PublishMinute.Items.FindByText(splitTime[1]));
				PublishAMPM.SelectedIndex = PublishAMPM.Items.IndexOf(PublishAMPM.Items.FindByText(splitTime[2]));
				
            }
            else
            {
                /*int hour1 = DateTime.Now.Hour;
                if (DateTime.Now.Hour > 12)
                {
                    hour1 = DateTime.Now.Hour - 12;
                }*/
				
				string currentTime = DateTime.Now.ToString("hh:mm:tt");
				
				string[] splitCurrentTime = currentTime.Split(':');
				PublishHour.SelectedIndex = PublishHour.Items.IndexOf(PublishHour.Items.FindByText(splitCurrentTime[0]));
				PublishMinute.SelectedIndex = PublishMinute.Items.IndexOf(PublishMinute.Items.FindByText(splitCurrentTime[1]));
				PublishAMPM.SelectedIndex = PublishAMPM.Items.IndexOf(PublishAMPM.Items.FindByText(splitCurrentTime[2]));
				/*
                string hour2 = hour1 < 10 ? ("0" + Convert.ToString(hour1)) : Convert.ToString(hour1);
                PublishHour.SelectedIndex = PublishHour.Items.IndexOf(PublishHour.Items.FindByText((Convert.ToString(hour2))));
                int minute = DateTime.Now.Minute;
                if (minute % 10 == 1)
                    minute = minute - 1;
                else if (minute % 10 == 2)
                    minute = minute - 2;
                else if (minute % 10 == 3)
                    minute = minute + 2;
                else if (minute % 10 == 4)
                    minute = minute + 1;
                else if (minute % 10 == 6)
                    minute = minute - 1;
                else if (minute % 10 == 7)
                    minute = minute - 2;
                else if (minute % 10 == 8)
                    minute = minute + 2;
                else if (minute % 10 == 9)
                    minute = minute + 1;
                string minutes = minute < 10 ? ("0" + Convert.ToString(minute)) : Convert.ToString(minute);
                //Response.Write(minutes);
                PublishMinute.SelectedIndex = PublishMinute.Items.IndexOf(PublishMinute.Items.FindByText(minutes));
                string ampm = DateTime.Now.ToString().Contains("AM") ? "AM" : "PM";
                PublishAMPM.SelectedIndex = PublishAMPM.Items.IndexOf(PublishAMPM.Items.FindByText(ampm));
                //Response.Write(hour2+" "+minutes+" "+ampm);*/
            }
            RecursiveHelper.FillAspNetTreeCheckBox(ref tvCategory, objArticle.Categories, true);

            List<ArticleToTagInfo> tags = (from t in ArticleToTagController.ListByArticle(articleId) select t).ToList();

            //Date
            if (!Null.IsNull(objArticle.PublishDate)) txtPublishDate.Text = objArticle.PublishDate.ToShortDateString();
            if (!Null.IsNull(objArticle.ExpireDate)) txtExpireDate.Text = objArticle.ExpireDate.ToShortDateString();

            cblViewRoles = Utils.FillRolesCheckBox(cblViewRoles, objArticle.ViewRoles, PortalSettings.AdministratorRoleId, PortalId);

            //rating 
            chkAllowRating.Checked = objArticle.AllowRating;
            cblRatingRoles = Utils.FillRolesCheckBox(cblRatingRoles, objArticle.RatingRoles, PortalSettings.AdministratorRoleId, PortalId);

            //Comment value
            chkAllowComment.Checked = objArticle.AllowComment;
            chkAutoAuthComment.Checked = objArticle.AutoAuthComment;
            cblCommentRoles = Utils.FillRolesCheckBox(cblCommentRoles, objArticle.CommentRoles, PortalSettings.AdministratorRoleId, PortalId);

            //
            chkAllowRecommend.Checked = objArticle.AllowRecommend;
            cblRecommendRoles = Utils.FillRolesCheckBox(cblRecommendRoles, objArticle.RecommendRoles, PortalSettings.AdministratorRoleId, PortalId);

            cblDownloadRoles = Utils.FillRolesCheckBox(cblDownloadRoles, objArticle.DownloadRoles, PortalSettings.AdministratorRoleId, PortalId);



            txtSummary.Text = objArticle.Summary;
            Editor1.Text = Server.HtmlDecode(objArticle.Article);
			BusinessLogic bConstructor = new BusinessLogic(articleId);
            //Response.Redirect("http://www.google.co.in?s=" + bConstructor.ArticleID.ToString(),false);
            chkPaging.Checked = bConstructor.IsPagingEnable;
			//chkPagination.Checked=false;
            AttachmentList = new List<AttachmentInfo>();
            List<AttachmentInfo> aiList = AttachmentController.ListByArticle(articleId);
            for (int i = 0; i < aiList.Count; i++)
            {
                AttachmentInfo ai = new AttachmentInfo();
                ai.Id = i;
                ai.ArticleId = articleId;
                ai.FilePath = aiList[i].FilePath;
                AttachmentList.Add(ai);
            }

            gvAttachment.DataSource = AttachmentList;
            gvAttachment.DataBind();

        }
        private void BindArticle(int articleId)
        {

            lblInvalidCategory.Visible = false;
            ArticleInfo objArticle = ArticleController.Get(articleId);

            if (objArticle == null)
            {
                return;
            }

            //Response.Write(objArticle.ctlima);
            txtTitle.Text = objArticle.Title;
            txtAuthor.Text = objArticle.Author;
            chkPublish.Checked = objArticle.Authed;
            /*
            txtSource.Text = objArticle.Source;
            chkQuote.Checked = objArticle.Quote;
            txtPinOrder.Text = Convert.ToString(objArticle.PinOrder);
            chkDraft.Checked = objArticle.Draft;

            ctlLinkUrl.Url = objArticle.LinkUrl;
            chkFeatured.Checked = objArticle.Featured;
            chkAuthed.Checked = objArticle.Authed;
            chkActive.Checked = objArticle.Active;
            */
            //bool returns = (objArticle.TopStoriesImage == "") ? true : false;

            //Page.ClientScript.RegisterStartupScript(this.GetType(), "mKey", "alert('" + objArticle.Image + "')", true);
            //Response.Write(objArticle.TopStoriesImage);
			txtKeywords.Text = objArticle.Keywords;
			txtImage.Text=objArticle.Image;
            /*if (!string.IsNullOrEmpty(objArticle.Image))
            {
                foreach (ListItem m in drpThumbnailImage.Items)
                {
                    if (m.Text == objArticle.Image.Remove(0, objArticle.Image.LastIndexOf("/") + 1))
                    {

                        drpThumbnailImage.SelectedValue = drpThumbnailImage.Items.FindByText(objArticle.Image.Remove(0, objArticle.Image.LastIndexOf("/") + 1)).Value;
                        break;
                    }
                }
            }*/
			/*
            if (!string.IsNullOrEmpty(objArticle.TopStoriesImage))
            {
                foreach (ListItem m in d1.Items)
                {
                    if (m.Text == objArticle.TopStoriesImage.Remove(0, objArticle.TopStoriesImage.LastIndexOf("/") + 1))
                    {
                        d1.SelectedValue = d1.Items.FindByText(objArticle.TopStoriesImage.Remove(0, objArticle.TopStoriesImage.LastIndexOf("/") + 1)).Value;
                        break;
                    }
                }
            }
            else
            {
                d1.SelectedIndex = 0;
            }*/
            if (!Null.IsNull(objArticle.PublishDate.ToString()))
            {
                string time = Convert.ToDateTime(objArticle.PublishDate).ToString("hh:mm:tt");
				string[] splitTime = time.Split(':');
                // Response.Write("Welcome");
                // Response.Write(time.Substring(0, 2) + " " + time.Substring(3, 2) + " " + time.Substring(6, 2) + " " + objArticle.Id);

                PublishHour.SelectedIndex = PublishHour.Items.IndexOf(PublishHour.Items.FindByText(splitTime[0]));
				PublishMinute.SelectedIndex = PublishMinute.Items.IndexOf(PublishMinute.Items.FindByText(splitTime[1]));
				PublishAMPM.SelectedIndex = PublishAMPM.Items.IndexOf(PublishAMPM.Items.FindByText(splitTime[2]));
				
            }
            else
            {
                /*int hour1 = DateTime.Now.Hour;
                if (DateTime.Now.Hour > 12)
                {
                    hour1 = DateTime.Now.Hour - 12;
                }*/
				
				string currentTime = DateTime.Now.ToString("hh:mm:tt");
				
				string[] splitCurrentTime = currentTime.Split(':');
				PublishHour.SelectedIndex = PublishHour.Items.IndexOf(PublishHour.Items.FindByText(splitCurrentTime[0]));
				PublishMinute.SelectedIndex = PublishMinute.Items.IndexOf(PublishMinute.Items.FindByText(splitCurrentTime[1]));
				PublishAMPM.SelectedIndex = PublishAMPM.Items.IndexOf(PublishAMPM.Items.FindByText(splitCurrentTime[2]));
				/*
                string hour2 = hour1 < 10 ? ("0" + Convert.ToString(hour1)) : Convert.ToString(hour1);
                PublishHour.SelectedIndex = PublishHour.Items.IndexOf(PublishHour.Items.FindByText((Convert.ToString(hour2))));
                int minute = DateTime.Now.Minute;
                if (minute % 10 == 1)
                    minute = minute - 1;
                else if (minute % 10 == 2)
                    minute = minute - 2;
                else if (minute % 10 == 3)
                    minute = minute + 2;
                else if (minute % 10 == 4)
                    minute = minute + 1;
                else if (minute % 10 == 6)
                    minute = minute - 1;
                else if (minute % 10 == 7)
                    minute = minute - 2;
                else if (minute % 10 == 8)
                    minute = minute + 2;
                else if (minute % 10 == 9)
                    minute = minute + 1;
                string minutes = minute < 10 ? ("0" + Convert.ToString(minute)) : Convert.ToString(minute);
                //Response.Write(minutes);
                PublishMinute.SelectedIndex = PublishMinute.Items.IndexOf(PublishMinute.Items.FindByText(minutes));
                string ampm = DateTime.Now.ToString().Contains("AM") ? "AM" : "PM";
                PublishAMPM.SelectedIndex = PublishAMPM.Items.IndexOf(PublishAMPM.Items.FindByText(ampm));
                //Response.Write(hour2+" "+minutes+" "+ampm);*/
            }
            /*
            
            
            */
            //if (objArticle.TopStoriesImage != "")
            //{
            //    drpTopStoriesPosition.SelectedValue = drpTopStoriesPosition.Items.FindByText(objArticle.TopStoriesImage.Remove(0, objArticle.TopStoriesImage.LastIndexOf("/") + 1)).Value;
            //}


            //Image

            /*
            SqlCommand cmd1 = new SqlCommand("Select ca.Image from CrossArticle_Article ca where ca.Id=@article", con.Set_Connection());
            cmd1.Parameters.AddWithValue("@article", articleId);
            SqlDataAdapter adap2 = new SqlDataAdapter(cmd1);
            DataTable dtt1 = new DataTable();
            adap2.Fill(dtt1);
            if (dtt1.Rows[0][0].ToString() != "")
            {
                if (UserInfo.IsInRole(PortalSettings.AdministratorRoleName))
                {
                    //ctlImage.Url = objArticle.Image;
                    i = cboFiles.Items.IndexOf(cboFiles.Items.FindByValue(Convert.ToString(dtt1.Rows[0][0].ToString())));
                    cboFiles.SelectedIndex = i;
                }
                else
                {
                    i = cboFiles.Items.IndexOf(cboFiles.Items.FindByValue(Convert.ToString(dtt1.Rows[0][0].ToString())));
                    cboFiles.SelectedIndex = i;
                    //URL1.Url = objArticle.Image;
                    //ctlUserImage.Url = objArticle.Image;
                }
            }
            */


            //txtImageDescription.Text = objArticle.ImageDescription;
            RecursiveHelper.FillAspNetTreeCheckBox(ref tvCategory, objArticle.Categories, true);

            List<ArticleToTagInfo> tags = (from t in ArticleToTagController.ListByArticle(articleId) select t).ToList();
            SqlCommand cmd = new SqlCommand("Select a2t.TagId from CrossArticle_ArticleToTag a2t where a2t.ArticleId=@article", new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString));
            cmd.Parameters.AddWithValue("@article", articleId);
            foreach (ListItem i in CheckBoxList1.Items)
            {
                i.Selected = false;
            }
            SqlDataAdapter adap1 = new SqlDataAdapter(cmd);
            DataTable dtt = new DataTable();
            adap1.Fill(dtt);
            foreach (DataRow r in dtt.Rows)
            {
                //Response.Write(r[0].ToString());
                CheckBoxList1.Items[(Convert.ToInt32(r[0].ToString())) - 1].Selected = true;
            }

            //Date
            if (!Null.IsNull(objArticle.PublishDate)) txtPublishDate.Text = objArticle.PublishDate.ToShortDateString();
            if (!Null.IsNull(objArticle.ExpireDate)) txtExpireDate.Text = objArticle.ExpireDate.ToShortDateString();

            cblViewRoles = Utils.FillRolesCheckBox(cblViewRoles, objArticle.ViewRoles, PortalSettings.AdministratorRoleId, PortalId);

            //rating 
            chkAllowRating.Checked = objArticle.AllowRating;
            cblRatingRoles = Utils.FillRolesCheckBox(cblRatingRoles, objArticle.RatingRoles, PortalSettings.AdministratorRoleId, PortalId);

            //Comment value
            chkAllowComment.Checked = objArticle.AllowComment;
            chkAutoAuthComment.Checked = objArticle.AutoAuthComment;
            cblCommentRoles = Utils.FillRolesCheckBox(cblCommentRoles, objArticle.CommentRoles, PortalSettings.AdministratorRoleId, PortalId);

            //
            chkAllowRecommend.Checked = objArticle.AllowRecommend;
            cblRecommendRoles = Utils.FillRolesCheckBox(cblRecommendRoles, objArticle.RecommendRoles, PortalSettings.AdministratorRoleId, PortalId);

            cblDownloadRoles = Utils.FillRolesCheckBox(cblDownloadRoles, objArticle.DownloadRoles, PortalSettings.AdministratorRoleId, PortalId);


			BusinessLogic bConstructor = new BusinessLogic(Convert.ToInt32(ArticleId));
            chkPaging.Checked = bConstructor.IsPagingEnable;
            
            txtSummary.Text = objArticle.Summary;
            Editor1.Text = Server.HtmlDecode(objArticle.Article);

            AttachmentList = new List<AttachmentInfo>();
            List<AttachmentInfo> aiList = AttachmentController.ListByArticle(articleId);
            for (int i = 0; i < aiList.Count; i++)
            {
                AttachmentInfo ai = new AttachmentInfo();
                ai.Id = i;
                ai.ArticleId = articleId;
                ai.FilePath = aiList[i].FilePath;
                AttachmentList.Add(ai);
            }

            gvAttachment.DataSource = AttachmentList;
            gvAttachment.DataBind();

        }
    /// <summary>
    /// Gets the file from version history.
    /// </summary>
    /// <param name="attachmentGuid">Atachment GUID</param>
    /// <param name="versionHistoryId">Version history ID</param>
    protected AttachmentInfo GetFile(Guid attachmentGuid, int versionHistoryId)
    {
        VersionManager vm = VersionManager.GetInstance(TreeProvider);

        // Get the attachment version
        AttachmentHistoryInfo attachmentVersion = vm.GetAttachmentVersion(versionHistoryId, attachmentGuid);
        if (attachmentVersion == null)
        {
            return null;
        }
        else
        {
            // Create the attachment object from the version
            AttachmentInfo ai = new AttachmentInfo(attachmentVersion.Generalized.DataClass);
            ai.AttachmentVersionHistoryID = versionHistoryId;
            return ai;
        }
    }
Beispiel #9
0
        /// <summary>
        /// 添加附件
        /// </summary>
        /// <param name="savedfileName">上传之后保存的文件名称</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="creinfo">认证信息</param>
        /// <returns>返回当前插入的附件id</returns>
        private int AddAttachment(string savedFileName, string fileName, CredentialInfo creinfo)
        {
            string         UploadDir      = GetUploadFolder(savedFileName, creinfo.ForumID.ToString());
            AttachmentInfo attachmentinfo = new AttachmentInfo();
            string         fileextname    = Utils.CutString(savedFileName, savedFileName.LastIndexOf(".") + 1).ToLower();
            Random         random         = new Random(unchecked ((int)DateTime.Now.Ticks));
            string         newfilename    = string.Format("{0}{1}{2}.{3}",
                                                          (Environment.TickCount & int.MaxValue).ToString(),
                                                          random.Next(1000, 99999), random.Next(1000, 99999), fileextname);

            try
            {
                // 如果是bmp jpg png图片类型
                if ((fileextname == "bmp" || fileextname == "jpg" || fileextname == "jpeg" || fileextname == "png"))
                {
                    if (Discuz.Common.Utils.FileExists(UploadDir + savedFileName))
                    {
                        System.Drawing.Image img = System.Drawing.Image.FromFile(UploadDir + savedFileName);
                        //System.IO.File.Copy(UploadDir + savedFileName, UploadDir + newfilename, true);
                        if (config.Attachimgmaxwidth > 0 && img.Width > config.Attachimgmaxwidth)
                        {
                            attachmentinfo.Sys_noupload = "图片宽度为" + img.Width.ToString() + ", 系统允许的最大宽度为" + config.Attachimgmaxwidth.ToString();
                        }

                        if (config.Attachimgmaxheight > 0 && img.Height > config.Attachimgmaxheight)
                        {
                            attachmentinfo.Sys_noupload = "图片高度为" + img.Width.ToString() + ", 系统允许的最大高度为" + config.Attachimgmaxheight.ToString();
                        }

                        attachmentinfo.Width  = img.Width;
                        attachmentinfo.Height = img.Height;

                        if (config.Watermarkstatus == 0)
                        {
                            img.Dispose();
                            File.Move(UploadDir + savedFileName, UploadDir + newfilename);
                        }
                        else
                        {
                            if (config.Watermarktype == 1 && File.Exists(Utils.GetMapPath(BaseConfigs.GetForumPath + "watermark/" + config.Watermarkpic)))
                            {
                                Discuz.Forum.ForumUtils.AddImageSignPic(img, UploadDir + newfilename, Utils.GetMapPath(BaseConfigs.GetForumPath + "watermark/" + config.Watermarkpic), config.Watermarkstatus, config.Attachimgquality, config.Watermarktransparency);
                            }
                            else
                            {
                                string watermarkText;
                                watermarkText = config.Watermarktext.Replace("{1}", config.Forumtitle);
                                watermarkText = watermarkText.Replace("{2}", "http://" + DNTRequest.GetCurrentFullHost() + "/");
                                watermarkText = watermarkText.Replace("{3}", Utils.GetDate());
                                watermarkText = watermarkText.Replace("{4}", Utils.GetTime());

                                Discuz.Forum.ForumUtils.AddImageSignText(img, UploadDir + newfilename, watermarkText, config.Watermarkstatus, config.Attachimgquality, config.Watermarkfontname, config.Watermarkfontsize);
                            }
                            System.IO.File.Delete(UploadDir + savedFileName);
                        }
                        // 获得文件长度
                        attachmentinfo.Filesize = new FileInfo(UploadDir + newfilename).Length;
                    }
                }
                else
                {
                    System.IO.File.Move(UploadDir + savedFileName, UploadDir + newfilename);
                    attachmentinfo.Filesize = new FileInfo(UploadDir + newfilename).Length;
                }
            }
            catch {}

            if (Discuz.Common.Utils.FileExists(UploadDir + savedFileName))
            {
                attachmentinfo.Filesize = new FileInfo(UploadDir + savedFileName).Length;
                attachmentinfo.Filename = GetDirInfo(savedFileName, creinfo.ForumID.ToString()) + savedFileName;
            }

            if (Discuz.Common.Utils.FileExists(UploadDir + newfilename))
            {
                attachmentinfo.Filesize = new FileInfo(UploadDir + newfilename).Length;
                attachmentinfo.Filename = GetDirInfo(newfilename, creinfo.ForumID.ToString()) + newfilename;
            }

            //当支持FTP上传附件时
            if (FTPs.GetForumAttachInfo != null && FTPs.GetForumAttachInfo.Allowupload == 1)
            {
                attachmentinfo.Filename = FTPs.GetForumAttachInfo.Remoteurl + "/" + newfilename.Replace("\\", "/");
            }

            attachmentinfo.Uid          = creinfo.UserID;
            attachmentinfo.Description  = fileextname;
            attachmentinfo.Filetype     = GetContentType(fileextname);
            attachmentinfo.Attachment   = fileName;
            attachmentinfo.Downloads    = 0;
            attachmentinfo.Postdatetime = DateTime.Now.ToString();
            attachmentinfo.Sys_index    = 0;

            //return Discuz.Data.DatabaseProvider.GetInstance().CreateAttachment(attachmentinfo);
            return(Discuz.Data.Attachments.CreateAttachments(attachmentinfo));
        }
Beispiel #10
0
        protected override void ShowPage()
        {
            pagetitle = "附件下载";

            if (attachmentid == -1)
            {
                AddErrLine("无效的附件ID");
                return;
            }

            // 如果当前用户非管理员并且论坛设定了禁止下载附件时间段,当前时间如果在其中的一个时间段内,则不允许用户下载附件
            if (useradminid != 1 && usergroupinfo.Disableperiodctrl != 1)
            {
                string visitTime = "";
                if (Scoresets.BetweenTime(config.Attachbanperiods, out visitTime))
                {
                    AddErrLine("在此时间段( " + visitTime + " )内用户不可以下载附件");
                    return;
                }
            }

            if (DNTRequest.GetString("goodsattach").ToLower() == "yes")
            {
                GetGoodsAttachInfo(attachmentid);
            }
            else
            {
                // 获取该附件的信息
                attachmentinfo = Attachments.GetAttachmentInfo(attachmentid);
                if (attachmentinfo == null)
                {
                    AddErrLine("不存在的附件ID");
                    return;
                }
                //当前用户已上传但是还没有绑定到帖子的附件需要特殊处理,直接输出图片
                if ((userid > 0 || userid == -1) && userid == attachmentinfo.Uid && attachmentinfo.Tid == 0 && attachmentinfo.Filetype.StartsWith("image/"))
                {
                    HttpContext.Current.Response.Clear();
                    if (attachmentinfo.Filename.IndexOf("http") < 0)
                    {
                        HttpContext.Current.Response.TransmitFile(BaseConfigs.GetForumPath + "upload/" + attachmentinfo.Filename.Trim());
                    }
                    else
                    {
                        HttpContext.Current.Response.Redirect(attachmentinfo.Filename.Trim());
                    }

                    HttpContext.Current.Response.End();
                    return;
                }
                // 获取该主题的信息
                topic = Topics.GetTopicInfo(attachmentinfo.Tid);
                if (topic == null)
                {
                    AddErrLine("不存在的主题ID");
                    return;
                }

                ForumInfo forum = Forums.GetForumInfo(topic.Fid);
                pagetitle = Utils.RemoveHtml(forum.Name);
                if (!UserAuthority.VisitAuthority(forum, usergroupinfo, userid, ref msg))
                {
                    AddErrLine(msg);
                    if (userid == -1)
                    {
                        needlogin = true;
                    }
                    return;
                }

                //添加判断特殊用户的代码
                if (!UserAuthority.CheckUsertAttachAuthority(forum, usergroupinfo, userid, ref msg))
                {
                    AddErrLine(msg);
                    if (userid == -1)
                    {
                        needlogin = true;
                    }
                    return;
                }

                ismoder = Moderators.IsModer(useradminid, userid, forum.Fid);
                // 检查用户是否拥有足够的阅读权限
                if ((attachmentinfo.Readperm > usergroupinfo.Readaccess) && (attachmentinfo.Uid != userid) && (!ismoder))
                {
                    AddErrLine("您的阅读权限不够");
                    if (userid == -1)
                    {
                        needlogin = true;
                    }
                    return;
                }

                //检查附件是否存在
                if (attachmentinfo.Filename.IndexOf("http") < 0 && !File.Exists(Utils.GetMapPath(string.Format(@"{0}upload/{1}", BaseConfigs.GetForumPath, attachmentinfo.Filename))))
                {
                    AddErrLine("该附件文件不存在或已被删除");
                    return;
                }

                //(!Utils.IsImgFilename(attachmentinfo.Filename.Trim()) || config.Showimages != 1):判断文件是否是图片和图片是否允许在帖子中直接显示
                //userid != attachmentinfo.Uid && !ismoder:判断当前下载用户是否是该附件的发布者和当前用户是否具有管理权限
                //Utils.StrIsNullOrEmpty(Utils.GetCookie("dnt_attachment_" + attachmentid))当前用户是否已经下载过该附件
                if ((!Utils.IsImgFilename(attachmentinfo.Filename.Trim()) || config.Showimages != 1) &&
                    (userid != attachmentinfo.Uid && !ismoder && Utils.StrIsNullOrEmpty(Utils.GetCookie("dnt_attachment_" + attachmentid))))
                {
                    if (Scoresets.IsSetDownLoadAttachScore() && UserCredits.UpdateUserExtCreditsByDownloadAttachment(userid, 1) == -1)
                    {
                        string addExtCreditsTip = "";
                        if (EPayments.IsOpenEPayments())
                        {
                            addExtCreditsTip = "<br/><span><a href=\"usercpcreditspay.aspx\">点击充值积分</a></span>";
                        }
                        AddErrLine("您的积分不足" + addExtCreditsTip);
                        return;
                    }
                    //设置该附件已经下载的cookie
                    Utils.WriteCookie("dnt_attachment_" + attachmentid, "true", 5);
                }

                //检查附件是否存在
                if (AttachPaymentLogs.HasBoughtAttach(userid, usergroupinfo.Radminid, attachmentinfo))
                {
                    AddErrLine("该附件为交易附件, 请先行购买!");
                    return;
                }
                //如果是图片就不更新下载次数
                if (!Utils.IsImgFilename(attachmentinfo.Filename.Trim()))
                {
                    Attachments.UpdateAttachmentDownloads(attachmentid);
                }

                EntLibConfigInfo entLibConfigInfo = EntLibConfigs.GetConfig();
                //当使用企业版squid静态文件加速时
                if (attachmentinfo.Filename.IndexOf("http") < 0 && entLibConfigInfo != null && !Utils.StrIsNullOrEmpty(entLibConfigInfo.Attachmentdir))
                {
                    attachmentinfo.Filename = EntLibConfigs.GetConfig().Attachmentdir.TrimEnd('/') + "/" + attachmentinfo.Filename;
                }

                if (attachmentinfo.Filename.IndexOf("http") < 0)
                {   //当使用mongodb数据库存储附件及相关信息时
                    if (entLibConfigInfo != null && entLibConfigInfo.Cacheattachfiles.Enable && entLibConfigInfo.Cacheattachfiles.Attachpostid > 0 && entLibConfigInfo.Cacheattachfiles.Attachpostid < attachmentinfo.Pid)
                    {
                        Discuz.Cache.Data.DBCacheService.GetAttachFilesService().ResponseFile(attachmentinfo.Filename, Path.GetFileName(attachmentinfo.Attachment), attachmentinfo.Filetype);
                    }
                    else
                    {
                        Utils.ResponseFile(Utils.GetMapPath(BaseConfigs.GetForumPath + @"upload/" + attachmentinfo.Filename), Path.GetFileName(attachmentinfo.Attachment), attachmentinfo.Filetype);
                    }
                }
                else
                {
                    try //添加try语法, 以防止在并发访问情况下, 服务器端远程链接被关闭后出现应用程序 '警告'(事件查看器)
                    {
                        HttpContext.Current.Response.Clear();
                        HttpContext.Current.Response.Redirect(attachmentinfo.Filename.Trim());
                        HttpContext.Current.Response.End();
                    }
                    catch { }
                }
            }
        }
Beispiel #11
0
        public ActionResult UploadFiles()
        {
            AppSettingsReader reader      = new AppSettingsReader();
            string            storageroot = reader.GetValue("storageroot", typeof(string)).ToString();

            if (Request.Files == null || Request.Files.Count == 0)
            {
                return(Json(new { message = "请选择文件" }));
            }

            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];

                if (file.ContentLength == 0)
                {
                    return(Json(new { message = "文件不合法" }));
                }

                int size = file.ContentLength / 1024;
                if (size > 10240)
                {
                    return(Json(new { message = "单个文件大小超出限制,请不要超过10M" }));
                }
            }

            string date          = DateTime.Now.ToString("yyyyMMdd");
            string applicationid = User.Identity.GetAccount().RootApplicationId;
            string path          = Path.Combine(storageroot, applicationid, date);

            if (Directory.Exists(path) == false)
            {
                Directory.CreateDirectory(path);
            }

            List <object> list = new List <object>();

            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];

                string newfilename = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
                string fileName    = Path.Combine(path, newfilename);

                try
                {
                    file.SaveAs(fileName);

                    //文件信息存入数据库
                    AttachmentInfo info = new AttachmentInfo()
                    {
                        Name = newfilename,
                        Path = fileName,
                        Size = file.ContentLength
                    };

                    SaveAttachmentInfo(info);

                    list.Add(new
                    {
                        name = file.FileName,
                        url  = Url.Action("Transmit", "upload", new { id = info.Id }, Request.Url.Scheme),
                        size = GetFileSizeFriendly(file.ContentLength)
                    });
                }
                catch (Exception ex)
                {
                    Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                    return(Json(new { message = "上传出错" }));
                }
            }

            return(Json(new { message = "ok", urls = list }));
        }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        // Hide hidden button
        hdnPostback.Style.Add("display", "none");

        // Do no process special actions if there is no form
        if (Form == null)
        {
            return;
        }

        // ItemValue is GUID or file name (GUID + extension) when working with forms
        if (mValue.LastIndexOfCSafe(".") == -1)
        {
            Guid fileGuid = ValidationHelper.GetGuid(Value, Guid.Empty);
            if (fileGuid != Guid.Empty)
            {
                // Get the file record
                AttachmentInfo ai = Form.GetAttachment(fileGuid);
                if (ai != null)
                {
                    uploader.CurrentFileName = ai.AttachmentName;
                    if (string.IsNullOrEmpty(ai.AttachmentUrl))
                    {
                        uploader.CurrentFileUrl = "~/CMSPages/GetFile.aspx?guid=" + ai.AttachmentGUID;
                    }
                    else
                    {
                        uploader.CurrentFileUrl = ai.AttachmentUrl;
                    }

                    // Register dialog script
                    ScriptHelper.RegisterDialogScript(Page);

                    string jsFuncName;
                    string baseUrl;
                    int    width;
                    int    height;
                    string tooltip;

                    // Image attachment
                    if (ImageHelper.IsSupportedByImageEditor(ai.AttachmentExtension))
                    {
                        // Dialog URL for image editing
                        width      = 905;
                        height     = 670;
                        jsFuncName = "OpenImageEditor";
                        tooltip    = ResHelper.GetString("general.editimage");
                        baseUrl    = string.Format(!IsLiveSite ? "{0}/CMSModules/Content/CMSDesk/Edit/ImageEditor.aspx" : "{0}/CMSFormControls/LiveSelectors/ImageEditor.aspx", URLHelper.GetFullApplicationUrl());
                    }
                    else
                    {
                        // Dialog URL for editing metadata
                        width      = 700;
                        height     = 400;
                        jsFuncName = "OpenMetaEditor";
                        tooltip    = ResHelper.GetString("general.edit");
                        baseUrl    = string.Format(!IsLiveSite ? "{0}/CMSModules/Content/Attachments/Dialogs/MetaDataEditor.aspx" : "{0}/CMSModules/Content/Attachments/CMSPages/MetaDataEditor.aspx", URLHelper.GetFullApplicationUrl());
                    }

                    string script = "function " + jsFuncName + "(attachmentGuid, versionHistoryId, siteId, hash, clientid) {\n modalDialog('" + baseUrl + "?refresh=1&attachmentguid=' + attachmentGuid + (versionHistoryId > 0 ? '&versionhistoryid=' + versionHistoryId : '' ) + '&siteid=' + siteId + '&hash=' + hash + '&clientid=' + clientid, 'imageEditorDialog', " + width + ", " + height + ");\n return false;\n}";

                    // Dialog for attachment editing
                    ScriptHelper.RegisterClientScriptBlock(this, typeof(string), jsFuncName,
                                                           ScriptHelper.GetScript(script));

                    if (Form.Mode != FormModeEnum.InsertNewCultureVersion)
                    {
                        // Create security hash
                        string parameters = "?refresh=1&attachmentGUID=" + ai.AttachmentGUID;
                        if (ai.AttachmentVersionHistoryID > 0)
                        {
                            parameters += "&versionhistoryid=" + ai.AttachmentVersionHistoryID;
                        }
                        parameters += "&siteid=" + ai.AttachmentSiteID;
                        parameters += "&clientid=" + ClientID;

                        string validationHash = QueryHelper.GetHash(parameters);

                        // Setup uploader's action button - it opens image editor when clicked
                        uploader.ActionButton.Attributes.Add("onclick", string.Format("{0}('{1}', {2}, {3}, '{4}', '{5}'); return false;", jsFuncName, ai.AttachmentGUID, ai.AttachmentVersionHistoryID, ai.AttachmentSiteID, validationHash, ClientID));

                        uploader.ActionButton.ToolTip = tooltip;
                        uploader.ShowActionButton     = true;

                        // Initialize refresh script
                        string refresh = string.Format("function InitRefresh_{0}() {{ {1}; if (RefreshTree != null) RefreshTree(); }}", ClientID, Page.ClientScript.GetPostBackEventReference(hdnPostback, "refresh"));
                        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "AttachmentScripts_" + ClientID, ScriptHelper.GetScript(refresh));
                    }
                    else
                    {
                        uploader.ShowActionButton = false;
                    }
                }
            }
        }
        else
        {
            uploader.CurrentFileName = (Form is BizForm) ? ((BizForm)Form).GetFileNameForUploader(mValue) : FormHelper.GetOriginalFileName(mValue);
            uploader.CurrentFileUrl  = "~/CMSModules/BizForms/CMSPages/GetBizFormFile.aspx?filename=" + FormHelper.GetGuidFileName(mValue) + "&sitename=" + Form.SiteName;
        }

        if (Form != null)
        {
            // Register post back button for update panel
            if (Form.ShowImageButton && Form.SubmitImageButton.Visible)
            {
                ControlsHelper.RegisterPostbackControl(Form.SubmitImageButton);
            }
            else if (Form.SubmitButton.Visible)
            {
                ControlsHelper.RegisterPostbackControl(Form.SubmitButton);
            }
        }
    }
Beispiel #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="info"></param>
        /// <param name="isIncludeChildren"></param>
        /// <param name="isMutiple"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public AttachmentInfo SaveOrUpdate(AttachmentInfo info, bool isIncludeChildren = false, bool isMutiple = false)
        {
            if (info == null)
            {
                return(null);
            }

            AttachmentInfo attachmentInfo;

            if (info.Id > 0)
            {
                bool isUpdated = FILE_REPOSITORY.UpdateExecute(info);
                IEnumerable <AttachmentItem> deleteItems = FILE_REPOSITORY.GetItemsByFileId(info.Id).AsEnumerable();
                if (isUpdated)
                {
                    if (!isMutiple && info.Items != null && info.Items.Any()) //单附件上传需要清空掉数据
                    {
                        deleteItems.ForEach(item => FILE_REPOSITORY.DeleteExecute(item));
                    }
                    else if (isMutiple)
                    {
                        if (info.Items != null && info.Items.Any())
                        {
                            //如果是多附件上传 则删除新的集合中不存在的 保留原有的 添加最新上传的
                            deleteItems.ForEach(o =>
                            {
                                if (info.Items.Count(n => n.Id == o.Id) == 0)
                                {
                                    FILE_REPOSITORY.DeleteExecute(o);
                                }
                            });
                        }
                        else
                        {
                            deleteItems.ForEach(o => FILE_REPOSITORY.DeleteExecute(o));
                        }
                    }
                }

                attachmentInfo = info;
            }
            else
            {
                int id = FILE_REPOSITORY.AddExecute(info);

                attachmentInfo = FILE_REPOSITORY.GetById(id);

                attachmentInfo.Items = info.Items;
            }

            List <AttachmentItem> newItems = new List <AttachmentItem>();

            if (!isIncludeChildren)
            {
                return(attachmentInfo);
            }

            if (attachmentInfo.Items == null || !attachmentInfo.Items.Any())
            {
                return(attachmentInfo);
            }

            attachmentInfo.Items.ForEach(o => o.AttachmentInfoId = attachmentInfo.Id);

            foreach (var item in attachmentInfo.Items)
            {
                //如果是多附件上传 且当前的附件是旧附件 则不再保存 取出来实体即可
                if (item.Id > 0)
                {
                    AttachmentItem curItem = FILE_REPOSITORY.GetItemById(item.Id);

                    if (curItem != null)
                    {
                        curItem.IsOld = true;
                        newItems.Add(curItem);
                    }

                    continue;
                }

                AttachmentItem newItem = this.SaveOrUpdate(item);

                if (newItem == null)
                {
                    throw new ArgumentNullException("newItem", "newItem must be not null,please fix error");
                }

                newItem.Content = item.Content;
                newItem.Content.AttachmentItemId = newItem.Id;

                byte[] buffer = item.Content.Content;

                if (!item.IsDB)
                {
                    newItem.Content.Content = null;
                }

                newItem.Content         = this.SaveOrUpdate(newItem.Content);
                newItem.Content.Content = buffer;

                newItems.Add(newItem);
            }

            attachmentInfo.Items = newItems;

            return(attachmentInfo);
        }
Beispiel #14
0
 /// <summary>
 /// 查看用户是否购买过指定附件
 /// </summary>
 /// <param name="userid">购买用户id</param>
 /// <param name="aid">附件id</param>
 /// <returns></returns>
 public static bool HasBoughtAttach(int userid, int radminid, AttachmentInfo attachmentinfo)
 {
     //检查附件是否存在
     return(attachmentinfo.Attachprice > 0 && attachmentinfo.Uid != userid && radminid != 1 && !Data.AttachPaymentLogs.HasBoughtAttach(userid, attachmentinfo.Aid));
 }
Beispiel #15
0
        public bool IsAtSynchronizedSite(AttachmentInfo attachment)
        {
            var siteId = SiteInfoProvider.GetSiteID(Settings.Sitename);

            return(attachment.AttachmentSiteID == siteId);
        }
    /// <summary>
    /// Initializes common properties used for processing image.
    /// </summary>
    private void baseImageEditor_InitializeProperties()
    {
        var currentUser = MembershipContext.AuthenticatedUser;

        // Process attachment
        switch (baseImageEditor.ImageType)
        {
            // Process physical file
            case ImageHelper.ImageTypeEnum.PhysicalFile:
                {
                    if (!String.IsNullOrEmpty(filePath))
                    {
                        if ((currentUser != null) && currentUser.IsGlobalAdministrator)
                        {
                            try
                            {
                                // Load the file from disk
                                string physicalPath = Server.MapPath(filePath);
                                byte[] data = File.ReadAllBytes(physicalPath);
                                baseImageEditor.ImgHelper = new ImageHelper(data);
                            }
                            catch
                            {
                                baseImageEditor.LoadingFailed = true;
                                baseImageEditor.ShowError(GetString("img.errors.loading"));
                            }
                        }
                        else
                        {
                            baseImageEditor.LoadingFailed = true;
                            baseImageEditor.ShowError(GetString("img.errors.rights"));
                        }
                    }
                    else
                    {
                        baseImageEditor.LoadingFailed = true;
                        baseImageEditor.ShowError(GetString("img.errors.loading"));
                    }
                }
                break;

            // Process metafile
            case ImageHelper.ImageTypeEnum.Metafile:
                {
                    // Get metafile
                    mf = MetaFileInfoProvider.GetMetaFileInfoWithoutBinary(metafileGuid, CurrentSiteName, true);

                    // If file is not null and current user is global administrator then set image
                    if (mf != null)
                    {
                        if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, MembershipContext.AuthenticatedUser))
                        {
                            // Ensure metafile binary data
                            mf.MetaFileBinary = MetaFileInfoProvider.GetFile(mf, CurrentSiteName);
                            if (mf.MetaFileBinary != null)
                            {
                                baseImageEditor.ImgHelper = new ImageHelper(mf.MetaFileBinary);
                            }
                            else
                            {
                                baseImageEditor.LoadingFailed = true;
                                baseImageEditor.ShowError(GetString("img.errors.loading"));
                            }
                        }
                        else
                        {
                            baseImageEditor.LoadingFailed = true;
                            baseImageEditor.ShowError(GetString("img.errors.rights"));
                        }
                    }
                    else
                    {
                        baseImageEditor.LoadingFailed = true;
                        baseImageEditor.ShowError(GetString("img.errors.loading"));
                    }
                }
                break;

            default:
                {
                    baseImageEditor.Tree = new TreeProvider(currentUser);

                    // If using workflow then get versioned attachment
                    if (VersionHistoryID != 0)
                    {
                        // Get the versioned attachment
                        AttachmentHistoryInfo attachmentVersion = VersionManager.GetAttachmentVersion(VersionHistoryID, attachmentGuid);
                        if (attachmentVersion != null)
                        {
                            // Create new attachment object
                            ai = new AttachmentInfo(attachmentVersion.Generalized.DataClass);
                            if (ai != null)
                            {
                                AttachmentHistoryID = attachmentVersion.AttachmentHistoryID;
                                ai.AttachmentVersionHistoryID = VersionHistoryID;
                            }
                        }
                    }
                    // Else get file without binary data
                    else
                    {
                        ai = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(attachmentGuid, CurrentSiteName);
                    }

                    // If file is not null and current user is set
                    if (ai != null)
                    {
                        TreeNode node;
                        if (ai.AttachmentDocumentID > 0)
                        {
                            node = baseImageEditor.Tree.SelectSingleDocument(ai.AttachmentDocumentID);
                        }
                        else
                        {
                            // Get parent node ID in case attachment is edited for document not created yet
                            int parentNodeId = QueryHelper.GetInteger("parentId", 0);

                            node = baseImageEditor.Tree.SelectSingleNode(parentNodeId);
                        }

                        // If current user has appropriate permissions then set image - check hash fro live site otherwise check node permissions
                        if ((currentUser != null) && (node != null) && ((IsLiveSite && QueryHelper.ValidateHash("hash")) || (!IsLiveSite && (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed))))
                        {
                            // Ensure attachment binary data
                            if (VersionHistoryID == 0)
                            {
                                ai.AttachmentBinary = AttachmentInfoProvider.GetFile(ai, CurrentSiteName);
                            }

                            if (ai.AttachmentBinary != null)
                            {
                                baseImageEditor.ImgHelper = new ImageHelper(ai.AttachmentBinary);
                            }
                            else
                            {
                                baseImageEditor.LoadingFailed = true;
                                baseImageEditor.ShowError(GetString("img.errors.loading"));
                            }
                        }
                        else
                        {
                            baseImageEditor.LoadingFailed = true;
                            baseImageEditor.ShowError(GetString("img.errors.filemodify"));
                        }
                    }
                    else
                    {
                        baseImageEditor.LoadingFailed = true;
                        baseImageEditor.ShowError(GetString("img.errors.loading"));
                    }
                }
                break;
        }

        // Check that image is in supported formats
        if ((!baseImageEditor.LoadingFailed) && (baseImageEditor.ImgHelper.ImageFormatToString() == null))
        {
            baseImageEditor.LoadingFailed = true;
            baseImageEditor.ShowError(GetString("img.errors.format"));
        }

        // Disable editor if loading failed
        if (baseImageEditor.LoadingFailed)
        {
            Enabled = false;
        }
    }
    /// <summary>
    /// Saves modified image data.
    /// </summary>
    /// <param name="name">Image name</param>
    /// <param name="extension">Image extension</param>
    /// <param name="mimetype">Image mimetype</param>
    /// <param name="title">Image title</param>
    /// <param name="description">Image description</param>
    /// <param name="binary">Image binary data</param>
    /// <param name="width">Image width</param>
    /// <param name="height">Image height</param>
    private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height)
    {
        LoadInfos();

        // Save image data depending to image type
        switch (baseImageEditor.ImageType)
        {
            // Process attachment
            case ImageHelper.ImageTypeEnum.Attachment:
                if (ai != null)
                {
                    // Save new data
                    try
                    {
                        // Get the node
                        TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree);

                        // Check Create permission when saving temporary attachment, check Modify permission else
                        NodePermissionsEnum permissionToCheck = (ai.AttachmentFormGUID == Guid.Empty) ? NodePermissionsEnum.Modify : NodePermissionsEnum.Create;

                        // Check permission
                        if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed)
                        {
                            baseImageEditor.ShowError(GetString("attach.actiondenied"));
                            SavingFailed = true;

                            return;
                        }

                        if (!IsNameUnique(name, extension))
                        {
                            baseImageEditor.ShowError(GetString("img.namenotunique"));
                            SavingFailed = true;

                            return;
                        }

                        // Ensure automatic check-in/ check-out
                        bool useWorkflow = false;
                        bool autoCheck = false;
                        WorkflowManager workflowMan = WorkflowManager.GetInstance(baseImageEditor.Tree);
                        if (node != null)
                        {
                            // Get workflow info
                            WorkflowInfo wi = workflowMan.GetNodeWorkflow(node);

                            // Check if the document uses workflow
                            if (wi != null)
                            {
                                useWorkflow = true;
                                autoCheck = !wi.UseCheckInCheckOut(CurrentSiteName);
                            }

                            // Check out the document
                            if (autoCheck)
                            {
                                VersionManager.CheckOut(node, node.IsPublished, true);
                                VersionHistoryID = node.DocumentCheckedOutVersionHistoryID;
                            }

                            // Workflow has been lost, get published attachment
                            if (useWorkflow && (VersionHistoryID == 0))
                            {
                                ai = AttachmentInfoProvider.GetAttachmentInfo(ai.AttachmentGUID, CurrentSiteName);
                            }

                            // If extension changed update CMS.File extension
                            if ((node.NodeClassName.ToLowerCSafe() == "cms.file") && (node.DocumentExtensions != extension))
                            {
                                // Update document extensions if no custom are used
                                if (!node.DocumentUseCustomExtensions)
                                {
                                    node.DocumentExtensions = extension;
                                }
                                node.SetValue("DocumentType", extension);

                                DocumentHelper.UpdateDocument(node, baseImageEditor.Tree);
                            }
                        }

                        if (ai != null)
                        {
                            // Test all parameters to empty values and update new value if available
                            if (name != "")
                            {
                                if (!name.EndsWithCSafe(extension))
                                {
                                    ai.AttachmentName = name + extension;
                                }
                                else
                                {
                                    ai.AttachmentName = name;
                                }
                            }
                            if (extension != "")
                            {
                                ai.AttachmentExtension = extension;
                            }
                            if (mimetype != "")
                            {
                                ai.AttachmentMimeType = mimetype;
                            }

                            ai.AttachmentTitle = title;
                            ai.AttachmentDescription = description;

                            if (binary != null)
                            {
                                ai.AttachmentBinary = binary;
                                ai.AttachmentSize = binary.Length;
                            }
                            if (width > 0)
                            {
                                ai.AttachmentImageWidth = width;
                            }
                            if (height > 0)
                            {
                                ai.AttachmentImageHeight = height;
                            }
                            // Ensure object
                            ai.MakeComplete(true);
                            if (VersionHistoryID > 0)
                            {
                                VersionManager.SaveAttachmentVersion(ai, VersionHistoryID);
                            }
                            else
                            {
                                AttachmentInfoProvider.SetAttachmentInfo(ai);

                                // Log the synchronization and search task for the document
                                if (node != null)
                                {
                                    // Update search index for given document
                                    if (DocumentHelper.IsSearchTaskCreationAllowed(node))
                                    {
                                        SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, node.GetSearchID(), node.DocumentID);
                                    }

                                    DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree);
                                }
                            }

                            // Check in the document
                            if ((autoCheck) && (VersionManager != null) && (VersionHistoryID > 0) && (node != null))
                            {
                                VersionManager.CheckIn(node, null);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message);
                        EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex);
                        SavingFailed = true;
                    }
                }
                break;

            case ImageHelper.ImageTypeEnum.PhysicalFile:
                if (!String.IsNullOrEmpty(filePath))
                {
                    var currentUser = MembershipContext.AuthenticatedUser;
                    if ((currentUser != null) && currentUser.IsGlobalAdministrator)
                    {
                        try
                        {
                            string physicalPath = Server.MapPath(filePath);
                            string newPath = physicalPath;

                            // Write binary data to the disk
                            File.WriteAllBytes(physicalPath, binary);

                            // Handle rename of the file
                            if (!String.IsNullOrEmpty(name))
                            {
                                newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(physicalPath), name);
                            }
                            if (!String.IsNullOrEmpty(extension))
                            {
                                string oldExt = Path.GetExtension(physicalPath);
                                newPath = newPath.Substring(0, newPath.Length - oldExt.Length) + extension;
                            }

                            // Move the file
                            if (newPath != physicalPath)
                            {
                                File.Move(physicalPath, newPath);
                            }
                        }
                        catch (Exception ex)
                        {
                            baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message);
                            EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex);
                            SavingFailed = true;
                        }
                    }
                    else
                    {
                        baseImageEditor.ShowError(GetString("img.errors.rights"));
                        SavingFailed = true;
                    }
                }
                break;

            // Process metafile
            case ImageHelper.ImageTypeEnum.Metafile:

                if (mf != null)
                {
                    if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, MembershipContext.AuthenticatedUser))
                    {
                        try
                        {
                            // Test all parameters to empty values and update new value if available
                            if (name.CompareToCSafe("") != 0)
                            {
                                if (!name.EndsWithCSafe(extension))
                                {
                                    mf.MetaFileName = name + extension;
                                }
                                else
                                {
                                    mf.MetaFileName = name;
                                }
                            }
                            if (extension.CompareToCSafe("") != 0)
                            {
                                mf.MetaFileExtension = extension;
                            }
                            if (mimetype.CompareToCSafe("") != 0)
                            {
                                mf.MetaFileMimeType = mimetype;
                            }

                            mf.MetaFileTitle = title;
                            mf.MetaFileDescription = description;

                            if (binary != null)
                            {
                                mf.MetaFileBinary = binary;
                                mf.MetaFileSize = binary.Length;
                            }
                            if (width > 0)
                            {
                                mf.MetaFileImageWidth = width;
                            }
                            if (height > 0)
                            {
                                mf.MetaFileImageHeight = height;
                            }

                            // Save new data
                            MetaFileInfoProvider.SetMetaFileInfo(mf);

                            if (RefreshAfterAction)
                            {
                                if (String.IsNullOrEmpty(externalControlID))
                                {
                                    baseImageEditor.LtlScript.Text = ScriptHelper.GetScript("Refresh();");
                                }
                                else
                                {
                                    baseImageEditor.LtlScript.Text = ScriptHelper.GetScript(String.Format("InitRefresh({0}, false, false, '{1}', 'refresh')", ScriptHelper.GetString(externalControlID), mf.MetaFileGUID));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message);
                            EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex);
                            SavingFailed = true;
                        }
                    }
                    else
                    {
                        baseImageEditor.ShowError(GetString("img.errors.rights"));
                        SavingFailed = true;
                    }
                }
                break;
        }
    }
Beispiel #18
0
    /// <summary>
    /// Adds the field to the form.
    /// </summary>
    /// <param name="node">Document node</param>
    /// <param name="compareNode">Document compare node</param>
    /// <param name="columnName">Column name</param>
    private void AddField(TreeNode node, TreeNode compareNode, string columnName)
    {
        FormFieldInfo ffi = null;

        if (fi != null)
        {
            ffi = fi.GetFormField(columnName);
        }

        TableCell valueCell = new TableCell();

        valueCell.EnableViewState = false;
        TableCell valueCompare = new TableCell();

        valueCompare.EnableViewState = false;
        TableCell labelCell = new TableCell();

        labelCell.EnableViewState = false;
        TextComparison comparefirst  = null;
        TextComparison comparesecond = null;
        bool           switchSides   = true;
        bool           loadValue     = true;
        bool           empty         = true;
        bool           allowLabel    = true;

        // Get the caption
        if ((columnName == UNSORTED) || (ffi != null))
        {
            AttachmentInfo aiCompare = null;

            // Compare attachments
            if ((columnName == UNSORTED) || (ffi.DataType == FormFieldDataTypeEnum.DocumentAttachments))
            {
                allowLabel = false;

                string title = null;
                if (columnName == UNSORTED)
                {
                    title = GetString("attach.unsorted") + ":";
                }
                else
                {
                    title = (String.IsNullOrEmpty(ffi.Caption) ? ffi.Name : ffi.Caption) + ":";
                }

                // Prepare DataSource for original node
                loadValue = false;

                dsAttachments = new AttachmentsDataSource();
                dsAttachments.DocumentVersionHistoryID = versionHistoryId;
                if (columnName != UNSORTED)
                {
                    dsAttachments.AttachmentGroupGUID = ffi.Guid;
                }
                dsAttachments.Path        = node.NodeAliasPath;
                dsAttachments.CultureCode = CMSContext.PreferredCultureCode;
                SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                dsAttachments.SiteName        = si.SiteName;
                dsAttachments.OrderBy         = "AttachmentOrder, AttachmentName, AttachmentHistoryID";
                dsAttachments.SelectedColumns = "AttachmentHistoryID, AttachmentGUID, AttachmentImageWidth, AttachmentImageHeight, AttachmentExtension, AttachmentName, AttachmentSize, AttachmentOrder, AttachmentTitle, AttachmentDescription";
                dsAttachments.IsLiveSite      = false;
                dsAttachments.DataSource      = null;
                dsAttachments.DataBind();

                // Get the attachments table
                attachments = GetAttachmentsTable((DataSet)dsAttachments.DataSource, versionHistoryId, node.DocumentID);

                // Prepare datasource for compared node
                if (compareNode != null)
                {
                    dsAttachmentsCompare = new AttachmentsDataSource();
                    dsAttachmentsCompare.DocumentVersionHistoryID = versionCompare;
                    if (columnName != UNSORTED)
                    {
                        dsAttachmentsCompare.AttachmentGroupGUID = ffi.Guid;
                    }
                    dsAttachmentsCompare.Path            = compareNode.NodeAliasPath;
                    dsAttachmentsCompare.CultureCode     = CMSContext.PreferredCultureCode;
                    dsAttachmentsCompare.SiteName        = si.SiteName;
                    dsAttachmentsCompare.OrderBy         = "AttachmentOrder, AttachmentName, AttachmentHistoryID";
                    dsAttachmentsCompare.SelectedColumns = "AttachmentHistoryID, AttachmentGUID, AttachmentImageWidth, AttachmentImageHeight, AttachmentExtension, AttachmentName, AttachmentSize, AttachmentOrder, AttachmentTitle, AttachmentDescription";
                    dsAttachmentsCompare.IsLiveSite      = false;
                    dsAttachmentsCompare.DataSource      = null;
                    dsAttachmentsCompare.DataBind();

                    // Get the table to compare
                    attachmentsCompare = GetAttachmentsTable((DataSet)dsAttachmentsCompare.DataSource, versionCompare, node.DocumentID);

                    // Switch the sides if older version is on the right
                    if (versionHistoryId > versionCompare)
                    {
                        Hashtable dummy = attachmentsCompare;
                        attachmentsCompare = attachments;
                        attachments        = dummy;
                    }

                    // Add comparison
                    AddTableComparison(attachments, attachmentsCompare, "<strong>" + title + "</strong>", true, true);
                }
                else
                {
                    // Normal display
                    if (attachments.Count != 0)
                    {
                        bool first = true;

                        foreach (DictionaryEntry item in attachments)
                        {
                            string itemValue = ValidationHelper.GetString(item.Value, null);
                            if (!String.IsNullOrEmpty(itemValue))
                            {
                                valueCell = new TableCell();
                                labelCell = new TableCell();

                                if (first)
                                {
                                    labelCell.Text = "<strong>" + String.Format(title, item.Key) + "</strong>";
                                    first          = false;
                                }
                                valueCell.Text = itemValue;

                                AddRow(labelCell, valueCell, null, even);
                                even = !even;
                            }
                        }
                    }
                }
            }
            // Compare single file attachment
            else if (ffi.DataType == FormFieldDataTypeEnum.File)
            {
                // Get the attachment
                AttachmentInfo ai = DocumentHelper.GetAttachment(ValidationHelper.GetGuid(node.GetValue(columnName), Guid.Empty), versionHistoryId, TreeProvider, false);

                if (compareNode != null)
                {
                    aiCompare = DocumentHelper.GetAttachment(ValidationHelper.GetGuid(compareNode.GetValue(columnName), Guid.Empty), versionCompare, TreeProvider, false);
                }

                loadValue = false;
                empty     = true;

                // Prepare text comparison controls
                if ((ai != null) || (aiCompare != null))
                {
                    string textorig = null;
                    if (ai != null)
                    {
                        textorig = CreateAttachment(ai.Generalized.DataClass, versionHistoryId);
                    }
                    string textcompare = null;
                    if (aiCompare != null)
                    {
                        textcompare = CreateAttachment(aiCompare.Generalized.DataClass, versionCompare);
                    }

                    comparefirst = new TextComparison();
                    comparefirst.SynchronizedScrolling = false;
                    comparefirst.IgnoreHTMLTags        = true;
                    comparefirst.ConsiderHTMLTagsEqual = true;
                    comparefirst.BalanceContent        = false;

                    comparesecond = new TextComparison();
                    comparesecond.SynchronizedScrolling = false;
                    comparesecond.IgnoreHTMLTags        = true;

                    // Source text must be older version
                    if (versionHistoryId < versionCompare)
                    {
                        comparefirst.SourceText      = textorig;
                        comparefirst.DestinationText = textcompare;
                    }
                    else
                    {
                        comparefirst.SourceText      = textcompare;
                        comparefirst.DestinationText = textorig;
                    }

                    comparefirst.PairedControl  = comparesecond;
                    comparesecond.RenderingMode = TextComparisonTypeEnum.DestinationText;

                    valueCell.Controls.Add(comparefirst);
                    valueCompare.Controls.Add(comparesecond);
                    switchSides = false;

                    // Add both cells
                    if (compareNode != null)
                    {
                        AddRow(labelCell, valueCell, valueCompare, switchSides, null, even);
                    }
                    // Add one cell only
                    else
                    {
                        valueCell.Controls.Clear();
                        Literal ltl = new Literal();
                        ltl.Text = textorig;
                        valueCell.Controls.Add(ltl);
                        AddRow(labelCell, valueCell, null, even);
                    }
                    even = !even;
                }
            }
        }

        if (allowLabel && (labelCell.Text == ""))
        {
            labelCell.Text = "<strong>" + columnName + ":</strong>";
        }

        if (loadValue)
        {
            string textcompare = null;

            switch (columnName.ToLowerCSafe())
            {
            // Document content - display content of editable regions and editable web parts
            case "documentcontent":
                EditableItems ei = new EditableItems();
                ei.LoadContentXml(ValidationHelper.GetString(node.GetValue(columnName), ""));

                // Add text comparison control
                if (compareNode != null)
                {
                    EditableItems eiCompare = new EditableItems();
                    eiCompare.LoadContentXml(ValidationHelper.GetString(compareNode.GetValue(columnName), ""));

                    // Create editable regions comparison
                    Hashtable hashtable;
                    Hashtable hashtableCompare;

                    // Source text must be older version
                    if (versionHistoryId < versionCompare)
                    {
                        hashtable        = ei.EditableRegions;
                        hashtableCompare = eiCompare.EditableRegions;
                    }
                    else
                    {
                        hashtable        = eiCompare.EditableRegions;
                        hashtableCompare = ei.EditableRegions;
                    }

                    // Add comparison
                    AddTableComparison(hashtable, hashtableCompare, "<strong>" + columnName + " ({0}):</strong>", false, false);

                    // Create editable webparts comparison
                    // Source text must be older version
                    if (versionHistoryId < versionCompare)
                    {
                        hashtable        = ei.EditableWebParts;
                        hashtableCompare = eiCompare.EditableWebParts;
                    }
                    else
                    {
                        hashtable        = eiCompare.EditableWebParts;
                        hashtableCompare = ei.EditableWebParts;
                    }

                    // Add comparison
                    AddTableComparison(hashtable, hashtableCompare, "<strong>" + columnName + " ({0}):</strong>", false, false);
                }
                // No compare node
                else
                {
                    // Editable regions
                    Hashtable hashtable = ei.EditableRegions;
                    if (hashtable.Count != 0)
                    {
                        foreach (DictionaryEntry region in hashtable)
                        {
                            string regionValue = ValidationHelper.GetString(region.Value, null);
                            if (!String.IsNullOrEmpty(regionValue))
                            {
                                string regionKey = ValidationHelper.GetString(region.Key, null);

                                valueCell = new TableCell();
                                labelCell = new TableCell();

                                labelCell.Text = "<strong>" + columnName + " (" + DictionaryHelper.GetFirstKey(regionKey) + "):</strong>";
                                valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(regionValue, false));

                                AddRow(labelCell, valueCell, null, even);
                                even = !even;
                            }
                        }
                    }

                    // Editable web parts
                    hashtable = ei.EditableWebParts;
                    if (hashtable.Count != 0)
                    {
                        foreach (DictionaryEntry part in hashtable)
                        {
                            string partValue = ValidationHelper.GetString(part.Value, null);
                            if (!String.IsNullOrEmpty(partValue))
                            {
                                string partKey = ValidationHelper.GetString(part.Key, null);
                                valueCell = new TableCell();
                                labelCell = new TableCell();

                                labelCell.Text = "<strong>" + columnName + " (" + DictionaryHelper.GetFirstKey(partKey) + "):</strong>";
                                valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(partValue, false));

                                AddRow(labelCell, valueCell, null, even);
                                even = !even;
                            }
                        }
                    }
                }

                break;

            // Others, display the string value
            default:
                // Shift date time values to user time zone
                object origobject = node.GetValue(columnName);
                string textorig   = null;
                if (origobject is DateTime)
                {
                    TimeZoneInfo usedTimeZone = null;
                    textorig = TimeZoneHelper.GetCurrentTimeZoneDateTimeString(ValidationHelper.GetDateTime(origobject, DateTimeHelper.ZERO_TIME), CurrentUser, CMSContext.CurrentSite, out usedTimeZone);
                }
                else
                {
                    textorig = ValidationHelper.GetString(origobject, "");
                }

                // Add text comparison control
                if (compareNode != null)
                {
                    // Shift date time values to user time zone
                    object compareobject = compareNode.GetValue(columnName);
                    if (compareobject is DateTime)
                    {
                        TimeZoneInfo usedTimeZone = null;
                        textcompare = TimeZoneHelper.GetCurrentTimeZoneDateTimeString(ValidationHelper.GetDateTime(compareobject, DateTimeHelper.ZERO_TIME), CurrentUser, CMSContext.CurrentSite, out usedTimeZone);
                    }
                    else
                    {
                        textcompare = ValidationHelper.GetString(compareobject, "");
                    }

                    comparefirst = new TextComparison();
                    comparefirst.SynchronizedScrolling = false;

                    comparesecond = new TextComparison();
                    comparesecond.SynchronizedScrolling = false;
                    comparesecond.RenderingMode         = TextComparisonTypeEnum.DestinationText;

                    // Source text must be older version
                    if (versionHistoryId < versionCompare)
                    {
                        comparefirst.SourceText      = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false));
                        comparefirst.DestinationText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textcompare, false));
                    }
                    else
                    {
                        comparefirst.SourceText      = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textcompare, false));
                        comparefirst.DestinationText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false));
                    }

                    comparefirst.PairedControl = comparesecond;

                    if (Math.Max(comparefirst.SourceText.Length, comparefirst.DestinationText.Length) < 100)
                    {
                        comparefirst.BalanceContent = false;
                    }

                    valueCell.Controls.Add(comparefirst);
                    valueCompare.Controls.Add(comparesecond);
                    switchSides = false;
                }
                else
                {
                    valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false));
                }

                empty = (String.IsNullOrEmpty(textorig)) && (String.IsNullOrEmpty(textcompare));
                break;
            }
        }

        if (!empty)
        {
            if (compareNode != null)
            {
                AddRow(labelCell, valueCell, valueCompare, switchSides, null, even);
                even = !even;
            }
            else
            {
                AddRow(labelCell, valueCell, null, even);
                even = !even;
            }
        }
    }
        protected void gvAttachment_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
        {

            int id = Convert.ToInt32(e.CommandArgument);
            AttachmentInfo ai = new AttachmentInfo();

            List<AttachmentInfo> list = AttachmentList;

            switch (e.CommandName)
            {
                case "DeleteItem":
                    list.RemoveAt(id);
                    //Minus 1
                    for (int i = id; i < list.Count; i++)
                    {
                        list[i].Id = list[i].Id - 1;
                    }

                    AttachmentList = list;
                    gvAttachment.DataSource = AttachmentList;
                    gvAttachment.DataBind();
                    break;
                default:
                    break;
            }


        }
Beispiel #20
0
        protected virtual AttachmentInfo GenerateFileReport(HttpContext context, GetFileReportDataHandler handler)
        {
            YZRequest request     = new YZRequest(context);
            string    fileid      = request.GetString("fileid");
            string    template    = request.GetString("template");
            int       tagfolderid = request.GetInt32("tagfolderid");
            string    name        = request.GetString("name");
            string    method      = request.GetString("method");
            string    reportType  = method.Substring(8, method.Length - 14);

            JObject jPost    = request.GetPostData <JObject>();
            JObject jProcess = (JObject)jPost["process"];
            JObject jChart   = (JObject)jPost["chart"];
            Image   chart    = this.GetImage(jChart);

            string           templatePath     = context.Server.MapPath(String.Format("~/YZSoft/BPA/processreport/templates/{0}/{1}", reportType, template));
            TemplateFileType templeteFileType = this.GetTemplateFileType(template);
            string           ext = System.IO.Path.GetExtension(template);

            AttachmentInfo attachment = new AttachmentInfo();

            attachment.Name = name + ext;
            attachment.Ext  = ext;

            DataSet dataset = handler.Invoke(fileid, tagfolderid, jProcess, chart);

            switch (templeteFileType)
            {
            case TemplateFileType.Excel:
                HSSFWorkbook book;
                using (System.IO.FileStream stream = new System.IO.FileStream(templatePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                {
                    book = new HSSFWorkbook(stream);
                }

                YZExcelGenerate.Fill(book, null, dataset);
                YZExcelGenerate.PrepareForOutput(book);
                attachment = AttachmentManager.SaveAsAttachment(book, attachment);
                break;

            default:
                XWPFDocument doc;
                using (System.IO.FileStream stream = new System.IO.FileStream(templatePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                {
                    doc = new XWPFDocument(stream);
                }
                WordGenerator.Fill(doc, dataset);
                attachment = AttachmentManager.SaveAsAttachment(doc, attachment);
                break;
            }

            YZSoft.FileSystem.File file = new YZSoft.FileSystem.File();
            file.FolderID = tagfolderid;
            file.FileID   = attachment.FileID;
            file.AddBy    = YZAuthHelper.LoginUserAccount;
            file.AddAt    = DateTime.Now;
            file.Flag     = "Generate";

            using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider)
            {
                using (IDbConnection cn = provider.OpenConnection())
                {
                    file.OrderIndex = YZSoft.FileSystem.DirectoryManager.GetFileNextOrderIndex(provider, cn, tagfolderid);
                    FileSystem.DirectoryManager.Insert(provider, cn, file);
                }
            }

            return(attachment);
        }
Beispiel #21
0
    /// <summary>
    /// Provides operations necessary to create and store new attachment.
    /// </summary>
    private void HandleAttachmentUpload(bool fieldAttachment)
    {
        TreeProvider tree = null;
        TreeNode     node = null;

        // New attachment
        AttachmentInfo newAttachment = null;

        string message     = string.Empty;
        bool   fullRefresh = false;

        try
        {
            // Get the existing document
            if (DocumentID != 0)
            {
                // Get document
                tree = new TreeProvider(CMSContext.CurrentUser);
                node = DocumentHelper.GetDocument(DocumentID, tree);
                if (node == null)
                {
                    throw new Exception("Given document doesn't exist!");
                }
            }


            #region "Check permissions"

            if (CheckPermissions)
            {
                CheckNodePermissions(node);
            }

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

            // Standard attachments
            if (DocumentID != 0)
            {
                // Ensure automatic check-in/check-out
                bool            useWorkflow = false;
                bool            autoCheck   = false;
                WorkflowManager workflowMan = WorkflowManager.GetInstance(tree);
                VersionManager  vm          = null;

                // Get workflow info
                WorkflowInfo wi = workflowMan.GetNodeWorkflow(node);

                // Check if the document uses workflow
                if (wi != null)
                {
                    useWorkflow = true;
                    autoCheck   = !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName);
                }

                // Check out the document
                if (autoCheck)
                {
                    // Get original step Id
                    int originalStepId = node.DocumentWorkflowStepID;

                    // Get current step info
                    WorkflowStepInfo si = workflowMan.GetStepInfo(node);
                    if (si != null)
                    {
                        // Decide if full refresh is needed
                        bool automaticPublish = wi.WorkflowAutoPublishChanges;
                        // Document is published or archived or uses automatic publish or step is different than original (document was updated)
                        fullRefresh = si.StepIsPublished || si.StepIsArchived || (automaticPublish && !si.StepIsPublished) || (originalStepId != node.DocumentWorkflowStepID);
                    }

                    vm = VersionManager.GetInstance(tree);
                    vm.CheckOut(node, node.IsPublished, true);
                }

                // Handle field attachment
                if (fieldAttachment)
                {
                    newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    // Update attachment field
                    DocumentHelper.UpdateDocument(node, tree);
                }
                // Handle grouped and unsorted attachments
                else
                {
                    // Grouped attachment
                    if (AttachmentGroupGUID != Guid.Empty)
                    {
                        newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }
                    // Unsorted attachment
                    else
                    {
                        newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }
                }

                // Check in the document
                if (autoCheck)
                {
                    if (vm != null)
                    {
                        vm.CheckIn(node, null, null);
                    }
                }

                // Log synchronization task if not under workflow
                if (!useWorkflow)
                {
                    DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree);
                }
            }

            // Temporary attachments
            if (FormGUID != Guid.Empty)
            {
                newAttachment = AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, CMSContext.CurrentSiteID, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
            }

            // Ensure properties update
            if ((newAttachment != null) && !InsertMode)
            {
                AttachmentGUID = newAttachment.AttachmentGUID;
            }

            if (newAttachment == null)
            {
                throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied.");
            }
        }
        catch (Exception ex)
        {
            message       = ex.Message;
            lblError.Text = message;
        }
        finally
        {
            // Call aftersave javascript if exists
            if ((string.IsNullOrEmpty(message)) && (newAttachment != null))
            {
                string closeString = "CloseDialog();";
                // Register wopener script
                ScriptHelper.RegisterWOpenerScript(Page);

                if (!String.IsNullOrEmpty(AfterSaveJavascript))
                {
                    string url      = null;
                    string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, CMSContext.CurrentSiteName);
                    if (node != null)
                    {
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                        if (si != null)
                        {
                            bool usePermanent = SettingsKeyProvider.GetBoolValue(si.SiteName + ".CMSUsePermanentURLs");
                            if (usePermanent)
                            {
                                url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName));
                            }
                            else
                            {
                                url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(saveName, node.NodeAliasPath));
                            }
                        }
                    }
                    else
                    {
                        url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName));
                    }
                    // Calling javascript function with parameters attachments url, name, width, height
                    string jsParams = "('" + url + "', '" + newAttachment.AttachmentName + "', '" + newAttachment.AttachmentImageWidth + "', '" + newAttachment.AttachmentImageHeight + "');";
                    string script   = "if ((wopener.parent != null) && (wopener.parent." + AfterSaveJavascript + " != null)){wopener.parent." + AfterSaveJavascript + jsParams + "}";
                    script += "else if (wopener." + AfterSaveJavascript + " != null){wopener." + AfterSaveJavascript + jsParams + "}";

                    ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refreshAfterSave", ScriptHelper.GetScript(script + closeString));
                }

                // Create attachment info string
                string attachmentInfo = "";
                if ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (IncludeNewItemInfo))
                {
                    attachmentInfo = newAttachment.AttachmentGUID.ToString();
                }

                // Ensure message text
                message = HTMLHelper.EnsureLineEnding(message, " ");

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", " + (fullRefresh ? "true" : "false") + ", false" + ((attachmentInfo != "") ? ", '" + attachmentInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}" + closeString));
            }
        }
    }
    /// <summary>
    /// Updates parameters used by Edit button when displaying image editor.
    /// </summary>
    /// <param name="attachmentGuidString">GUID identifying attachment</param>
    private void UpdateEditParameters(string attachmentGuidString)
    {
        if (ShowTooltip)
        {
            // Try to get attachment GUID
            var attGuid = ValidationHelper.GetGuid(attachmentGuidString, Guid.Empty);
            if (attGuid != Guid.Empty)
            {
                // Get attachment
                AttachmentInfo attInfo = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(attGuid, SiteName);
                if (attInfo != null)
                {
                    string attName    = attInfo.AttachmentName;
                    int    documentId = DocumentID;

                    // Get attachment URL
                    string attachmentUrl;

                    if (Node != null)
                    {
                        if (IsLiveSite && (documentId > 0))
                        {
                            attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetAttachmentUrl(attGuid, URLHelper.GetSafeFileName(attName, SiteContext.CurrentSiteName)));
                        }
                        else
                        {
                            attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetAttachmentUrl(attGuid, URLHelper.GetSafeFileName(attName, SiteContext.CurrentSiteName), null, VersionHistoryID));
                        }
                    }
                    else
                    {
                        attachmentUrl = ResolveUrl(DocumentHelper.GetAttachmentUrl(attGuid, VersionHistoryID));
                    }
                    attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

                    // Ensure correct URL for non-temporary attachments
                    if ((OriginalNodeSiteName != SiteContext.CurrentSiteName) && (documentId > 0))
                    {
                        attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "sitename", OriginalNodeSiteName);
                    }

                    // Generate new tooltip command
                    string newToolTip  = null;
                    string title       = attInfo.AttachmentTitle;
                    string description = attInfo.AttachmentDescription;

                    // Optionally trim attachment name
                    string attachmentName = TextHelper.LimitLength(attInfo.AttachmentName, ATTACHMENT_NAME_LIMIT);
                    int    imageWidth     = attInfo.AttachmentImageWidth;
                    int    imageHeight    = attInfo.AttachmentImageHeight;
                    bool   isImage        = ImageHelper.IsImage(attInfo.AttachmentExtension);

                    int    tooltipWidth = 300;
                    string url          = isImage ? attachmentUrl : null;

                    string tooltipBody = UIHelper.GetTooltip(url, imageWidth, imageHeight, title, attachmentName, description, null, ref tooltipWidth);
                    if (!string.IsNullOrEmpty(tooltipBody))
                    {
                        newToolTip = String.Format("Tip('{0}', WIDTH, -300)", tooltipBody);
                    }

                    // Get update script
                    string updateScript = String.Format("$cmsj(\"#{0}\").attr('onmouseover', '').unbind('mouseover').mouseover(function(){{ {1} }});", attGuid, newToolTip);

                    // Execute update
                    ScriptHelper.RegisterStartupScript(Page, typeof(Page), "AttachmentUpdateEdit", ScriptHelper.GetScript(updateScript));
                }
            }
        }
    }
        private void UpdateArticle()
        {
            ArticleInfo objArticle = ArticleController.Get(ArticleId);
            //Normal 
            objArticle.Title = txtTitle.Text;
            objArticle.Author = txtAuthor.Text;
			objArticle.Keywords = txtKeywords.Text;
            /*
            objArticle.Source = txtSource.Text;
            objArticle.Quote = chkQuote.Checked;
            objArticle.Draft = chkDraft.Checked;

            objArticle.LinkUrl = ctlLinkUrl.Url;
            objArticle.PinOrder = Convert.ToInt32(txtPinOrder.Text);
            //other
            if (ArticlePortalSettings.General.Portal_ArticleRequireApproval == true)
            {
                objArticle.Authed = chkAuthed.Checked;
            }
            else
            {
                objArticle.Authed = true;
            }
            objArticle.Featured = chkFeatured.Checked;
            objArticle.Active = chkActive.Checked;
            */
			objArticle.Image = txtImage.Text;
            objArticle.Thumbnail = txtImage.Text;
            
            //objArticle.TopStoriesImage = "/Portals/0/" + drpTopStoriesPosition.SelectedItem.Text;
			objArticle.TopStoriesImage = null;
			/*
            if (drpTopStoriesPosition.SelectedItem.Text != "")
            {
                objArticle.TopStoriesImage = "/Portals/0/" + drpTopStoriesPosition.SelectedItem.Text;
            }
            else
            {
                objArticle.TopStoriesImage = null;
            }*/
			objArticle.PublishTime = PublishHour.SelectedItem.Text + ":" + PublishMinute.SelectedItem.Text + " " + PublishAMPM.SelectedItem.Text;
            
            //if (objArticle.Image.StartsWith("FileID="))
            //{
            //    FileController fc = new FileController();
            //    DotNetNuke.Services.FileSystem.FileInfo fi = new DotNetNuke.Services.FileSystem.FileInfo();
            //    DotNetNuke.Entities.Portals.PortalController ctlPortal = new DotNetNuke.Entities.Portals.PortalController();
            //    DotNetNuke.Entities.Portals.PortalInfo pi = ctlPortal.GetPortal(PortalId);

            //    fi = GetFileInfoById(objArticle.Image);
            //    if (fi != null && System.IO.File.Exists(fi.PhysicalPath))
            //    {
            //        objArticle.Thumbnail = DotNetNuke.Common.Globals.ApplicationPath + "/" + pi.HomeDirectory + "/" + fi.Folder + fi.FileName;
            //        System.IO.FileInfo physicalFile = new System.IO.FileInfo(fi.PhysicalPath);

            //        if (!fi.FileName.ToLower().StartsWith("thumb_"))//文件没有以"thumb_"开头,则先查找是否存在以thumb_ 开头的同名图片
            //        {
            //            if (System.IO.File.Exists(physicalFile.DirectoryName + "\\" + "thumb_" + physicalFile.Name))//存在该文件,则自动指向
            //            {
            //                objArticle.Thumbnail = DotNetNuke.Common.Globals.ApplicationPath + "/" + pi.HomeDirectory + "/" + fi.Folder + "thumb_" + fi.FileName;
            //            }
            //            else//不存在,则生成该文件,然后指向
            //            {
            //                if (ArticlePortalSettings.General.Portal_ArticleGenerateThumb)
            //                {
            //                    Utils.ResizeImage(fi.PhysicalPath, ArticlePortalSettings.General.Portal_ArticleThumbnailSize, physicalFile.DirectoryName + "\\" + "thumb_" + physicalFile.Name);
            //                    objArticle.Thumbnail = DotNetNuke.Common.Globals.ApplicationPath + "/" + pi.HomeDirectory + "/" + fi.Folder + "thumb_" + fi.FileName;
            //                }
            //            }
            //        }
            //    }
            //}
            //Add Categories
            objArticle.Categories = RecursiveHelper.GetAspNetTreeCheckList(tvCategory);

            //Add Tags
            objArticle.Tags = "";
            TagInfo objTag = new TagInfo();
            List<int> tagList = new List<int>();
            foreach (ListItem li in CheckBoxList1.Items)
            {
                if (li.Selected)
                {
                    if (listData.InnerText == "")
                    {
                        objTag = TagController.GetByTag(li.Value.Trim());
                        tagList.Add(objTag.Id);
                    }
                }
            }
            var newTaglist = (from p in tagList select p).Distinct();//remove the  repeated tag item.

            foreach (int item in newTaglist)
            {
                objArticle.Tags += item.ToString() + ",";
            }
            objArticle.Tags = Utils.RemoveSeperator(objArticle.Tags, ",");
            //Tags end

            //date
            if ((txtPublishDate.Text != null) && (txtPublishDate.Text != ""))
            {
                objArticle.PublishDate = Convert.ToDateTime(txtPublishDate.Text);
            }
            else
            {
                objArticle.PublishDate = DateTime.Now;
            }
            if (txtExpireDate.Text != "")
            {
                objArticle.ExpireDate = Convert.ToDateTime(txtExpireDate.Text);
            }

            objArticle.ViewRoles = Utils.GetCheckedItems(cblViewRoles, PortalSettings.AdministratorRoleId);
            //Rating
            objArticle.AllowRating = chkAllowRating.Checked;
            objArticle.RatingRoles = Utils.GetCheckedItems(cblRatingRoles, PortalSettings.AdministratorRoleId);

            //Recommend
            objArticle.AllowRecommend = chkAllowRecommend.Checked;
            objArticle.RecommendRoles = Utils.GetCheckedItems(cblRecommendRoles, PortalSettings.AdministratorRoleId);


            //Comment
            objArticle.AllowComment = chkAllowComment.Checked;
            objArticle.CommentRoles = Utils.GetCheckedItems(cblCommentRoles, PortalSettings.AdministratorRoleId);
            objArticle.AutoAuthComment = chkAutoAuthComment.Checked;

            //Download roles
            objArticle.DownloadRoles = Utils.GetCheckedItems(cblDownloadRoles, PortalSettings.AdministratorRoleId);
            objArticle.Summary = LocalUtils.RemoveAllHtmlTags(txtSummary.Text);
            objArticle.Article = Editor1.Text.Replace("src=&quot;Portals", "src=&quot;/Portals");
            objArticle.Authed = chkPublish.Checked;
        
			BusinessLogic b = new BusinessLogic();
            //Response.Redirect("http://www.google.co.in?b=" + b.ArticleID.ToString(),false);
            b.ArticleID = ArticleId;
            b.IsPagingEnable = chkPaging.Checked;
            b.UpdateExtraFieldArticle();
            ArticleController.Update(objArticle);

            //Now processing attachment

            AttachmentController.DeleteByArticle(ArticleId); //delete attachment first.
            AttachmentInfo ai = new AttachmentInfo();
            foreach (AttachmentInfo item in AttachmentList)
            {
                ai.ArticleId = ArticleId;
                ai.FilePath = item.FilePath;
                AttachmentController.Add(ai);
            }
            //Reset all 
            // ArticleId = -1;
            AttachmentList = new List<AttachmentInfo>();
            gvAttachment.DataSource = AttachmentList;
            gvAttachment.DataBind();
			if (Session["ArticlePageEdit"] != null)
            {
				urlReferrer = Session["ArticlePageEdit"].ToString();
				Response.Write("URL: "+urlReferrer);
                Session.Clear();
                Response.Redirect(urlReferrer);
            }
        }
        void Objects_AttachmentUpdate(object sender, PrimEventArgs e)
        {
            Primitive prim = e.Prim;

            if (client.Self.LocalID == 0 ||
                prim.ParentID != client.Self.LocalID ||
                prim.NameValues == null) return;

            for (int i = 0; i < prim.NameValues.Length; i++)
            {
                if (prim.NameValues[i].Name == "AttachItemID")
                {
                    AttachmentInfo attachment = new AttachmentInfo();
                    attachment.Prim = prim;
                    attachment.InventoryID = new UUID(prim.NameValues[i].Value.ToString());
                    attachment.PrimID = prim.ID;

                    lock (attachments)
                    {
                        // Add new attachment info
                        if (!attachments.ContainsKey(attachment.InventoryID))
                        {
                            attachments.Add(attachment.InventoryID, attachment);

                        }
                        else
                        {
                            attachment = attachments[attachment.InventoryID];
                            if (attachment.Prim == null)
                            {
                                attachment.Prim = prim;
                            }
                        }

                        // Don't update the tree yet if we're still updating invetory tree from server
                        //if (!TreeUpdateInProgress)
                        {
                            if (Inventory.Contains(attachment.InventoryID))
                            {
                                if (attachment.Item == null)
                                {
                                    InventoryItem item = (InventoryItem)Inventory[attachment.InventoryID];
                                    attachment.Item = item;
                                }
                                if (!attachment.MarkedAttached)
                                {
                                    attachment.MarkedAttached = true;
                                }
                            }
                            else
                            {
                                client.Inventory.RequestFetchInventory(attachment.InventoryID, client.Self.AgentID);
                            }
                        }
                    }
                    break;
                }
            }
        }
    /// <summary>
    /// Gets an attachment and modifies its metadata(name, title and description). Called when the "Edit attachment metadata" button is pressed.
    /// Expects the "Create example document" and "Insert unsorted attachment" methods to be run first.
    /// </summary>
    private bool EditMetadata()
    {
        // Create a new instance of the Tree provider
        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

        // Get the example document
        TreeNode node = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/API-Example", "en-us");

        if (node != null)
        {
            string where = "AttachmentIsUnsorted = 1";
            string orderBy = "AttachmentLastModified DESC";

            // Get the document's unsorted attachments with the latest on top
            DataSet attachments = DocumentHelper.GetAttachments(node, where, orderBy, false, tree);

            if (!DataHelper.DataSourceIsEmpty(attachments))
            {
                // Create attachment info object from the first DataRow
                AttachmentInfo attachment = new AttachmentInfo(attachments.Tables[0].Rows[0]);

                // Edit its metadata
                attachment.AttachmentName += " - modified";
                attachment.AttachmentTitle += "Example title";
                attachment.AttachmentDescription += "This is an example of an unsorted attachment.";

                // Ensure that the attachment can be updated without supplying its binary data.
                attachment.AllowPartialUpdate = true;

                // Save the object into database
                AttachmentInfoProvider.SetAttachmentInfo(attachment);

                return true;
            }
            else
            {
                apiEditMetadata.ErrorMessage = "No attachments were found.";
            }
        }

        return false;
    }
        public bool IsAttached(InventoryItem item)
        {
            List<Primitive> myAtt = client.Network.CurrentSim.ObjectsPrimitives.FindAll((Primitive p) => p.ParentID == client.Self.LocalID);
            foreach (Primitive prim in myAtt)
            {
                if (prim.NameValues == null) continue;
                UUID invID = UUID.Zero;
                for (int i = 0; i < prim.NameValues.Length; i++)
                {
                    if (prim.NameValues[i].Name == "AttachItemID")
                    {
                        invID = (UUID)prim.NameValues[i].Value.ToString();
                        break;
                    }
                }
                if (invID == item.UUID)
                {
                    lock (attachments)
                    {
                        AttachmentInfo inf = new AttachmentInfo();
                        inf.InventoryID = item.UUID;
                        inf.Item = item;
                        inf.MarkedAttached = true;
                        inf.Prim = prim;
                        inf.PrimID = prim.ID;
                        attachments[invID] = inf;
                    }
                    return true;
                }
            }

            return false;
        }
    /// <summary>
    /// Deletes all the example document's attachments. Called when the "Delete attachments" button is pressed.
    /// Expects the "CreateExampleDocument" and "InsertUnsortedAttachment" or "InsertFieldAttachment" method to be run first.
    /// </summary>
    private bool DeleteAttachments()
    {
        // Create a new instance of the Tree provider
        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

        // Get the example document
        TreeNode node = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/API-Example", "en-us");

        if (node != null)
        {
            // Get the document's unsorted attachments with the latest on top
            DataSet attachments = DocumentHelper.GetAttachments(node, null, null, false, tree);

            if (!DataHelper.DataSourceIsEmpty(attachments))
            {
                foreach (DataRow attachmentRow in attachments.Tables[0].Rows)
                {
                    // Create attachment info object from the first DataRow
                    AttachmentInfo attachment = new AttachmentInfo(attachmentRow);

                    // Delete the attachment
                    DocumentHelper.DeleteAttachment(node, attachment.AttachmentGUID, tree);
                }

                return true;
            }
            else
            {
                apiDeleteAttachments.ErrorMessage = "No attachments found.";
            }
        }

        return false;
    }
        public ICollection<AttachmentInfo> GetAttachments()
        {
            List<Primitive> myAtt = client.Network.CurrentSim.ObjectsPrimitives.FindAll((Primitive p) => p.ParentID == client.Self.LocalID);
            foreach (Primitive prim in myAtt)
            {
                if (prim.NameValues == null) continue;
                UUID invID = UUID.Zero;
                for (int i = 0; i < prim.NameValues.Length; i++)
                {
                    if (prim.NameValues[i].Name == "AttachItemID")
                    {
                        invID = (UUID)prim.NameValues[i].Value.ToString();
                        break;
                    }
                }
                var item = Inventory.GetNodeFor(invID).Data as InventoryItem;
                {
                    lock (attachments)
                    {
                        AttachmentInfo inf = new AttachmentInfo();
                        inf.InventoryID = invID;
                        inf.Item = item;
                        inf.MarkedAttached = true;
                        inf.Prim = prim;
                        inf.PrimID = prim.ID;
                        attachments[invID] = inf;
                    }
                }
            }

            return attachments.Values;
        }
    /// <summary>
    /// Initializes properties.
    /// </summary>
    private void InitializeAttachment()
    {
        AttachmentInfo attachmentInfo = null;

        if (InfoObject != null)
        {
            attachmentInfo = InfoObject as AttachmentInfo;
        }
        else
        {
            // If using workflow then get versioned attachment
            if (VersionHistoryID != 0)
            {
                // Get the versioned attachment with binary data
                AttachmentHistoryInfo attachmentHistory = VersionManager.GetAttachmentVersion(VersionHistoryID, ObjectGuid, false);
                if (attachmentHistory == null)
                {
                    attachmentInfo = null;
                }
                else
                {
                    // Create new attachment object
                    attachmentInfo = new AttachmentInfo(attachmentHistory.Generalized.DataClass);
                    attachmentInfo.AttachmentID = attachmentHistory.AttachmentHistoryID;
                }
            }
            // else get file without binary data
            else
            {
                attachmentInfo = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(ObjectGuid, SiteName);
            }

            InfoObject = attachmentInfo;
        }

        if (attachmentInfo != null)
        {
            // Check permissions
            if (CheckPermissions)
            {
                // If attachment is temporary, check 'Create' permission on parent node. Else check 'Modify' permission.
                NodePermissionsEnum permission = nodeIsParent ? NodePermissionsEnum.Create : NodePermissionsEnum.Modify;

                if (Node == null)
                {
                    RedirectToInformation(GetString("editeddocument.notexists"));
                }

                if (CMSContext.CurrentUser.IsAuthorizedPerDocument(Node, permission) != AuthorizationResultEnum.Allowed)
                {
                    RedirectToAccessDenied(GetString("metadata.errors.filemodify"));
                }
            }

            // Fire event GetObjectExtension
            if (GetObjectExtension != null)
            {
                GetObjectExtension(attachmentInfo.AttachmentExtension);
            }
        }
        else
        {
            RedirectToInformation(GetString("editedobject.notexists"));
        }
    }
    /// <summary>
    /// Gets the new output file object.
    /// </summary>
    /// <param name="ai">AttachmentInfo</param>
    /// <param name="data">Output file data</param>
    public CMSOutputAttachment NewOutputFile(AttachmentInfo ai, byte[] data)
    {
        CMSOutputAttachment attachment = new CMSOutputAttachment(ai, data);

        attachment.Watermark = Watermark;
        attachment.WatermarkPosition = WatermarkPosition;

        return attachment;
    }
    /// <summary>
    /// Handles attachment edit action.
    /// </summary>
    /// <param name="argument">Attachment GUID coming from view control</param>
    private void HandleAttachmentEdit(string argument)
    {
        IsEditImage = true;

        if (!string.IsNullOrEmpty(argument))
        {
            string[] argArr = argument.Split('|');

            Guid attachmentGuid = ValidationHelper.GetGuid(argArr[1], Guid.Empty);

            AttachmentInfo ai = null;

            int versionHistoryId = 0;
            if (TreeNodeObj != null)
            {
                versionHistoryId = TreeNodeObj.DocumentCheckedOutVersionHistoryID;
            }

            if (versionHistoryId == 0)
            {
                ai = AttachmentManager.GetAttachmentInfo(attachmentGuid, CMSContext.CurrentSiteName);
            }
            else
            {
                VersionManager vm = new VersionManager(TreeNodeObj.TreeProvider);
                if (vm != null)
                {
                    // Get the attachment version data
                    AttachmentHistoryInfo attachmentVersion = vm.GetAttachmentVersion(versionHistoryId, attachmentGuid, false);
                    if (attachmentVersion == null)
                    {
                        ai = null;
                    }
                    else
                    {
                        // Create the attachment info from given data
                        ai = new AttachmentInfo(attachmentVersion.Generalized.DataClass);
                        ai.AttachmentID = attachmentVersion.AttachmentHistoryID;
                    }
                    if (ai != null)
                    {
                        ai.AttachmentLastHistoryID = versionHistoryId;
                    }
                }
            }

            if (ai != null)
            {
                string nodeAliasPath = "";
                if (TreeNodeObj != null)
                {
                    nodeAliasPath = TreeNodeObj.NodeAliasPath;
                }

                string url = mediaView.GetAttachmentItemUrl(ai.AttachmentGUID, ai.AttachmentName, nodeAliasPath, ai.AttachmentImageHeight, ai.AttachmentImageWidth, 0);

                if (LastAttachmentGuid == attachmentGuid)
                {
                    SelectMediaItem(ai.AttachmentName, ai.AttachmentExtension, ai.AttachmentImageWidth, ai.AttachmentImageHeight, ai.AttachmentSize, url);
                }

                // Update select action to reflect changes made during editing
                LoadDataSource();
                mediaView.Reload();
                pnlUpdateView.Update();
            }
        }

        ClearActionElems();
    }
 public override IOptimizerResult Optimize(AttachmentInfo file)
 {
     return ProcessStream(file.AttachmentBinary);
 }
    /// <summary>
    /// Ensures the info objects.
    /// </summary>
    private void LoadInfos()
    {
        switch (baseImageEditor.ImageType)
        {
            case ImageHelper.ImageTypeEnum.Metafile:

                if (mf == null)
                {
                    mf = MetaFileInfoProvider.GetMetaFileInfoWithoutBinary(metafileGuid, CurrentSiteName, true);
                }
                break;

            case ImageHelper.ImageTypeEnum.PhysicalFile:
                // Skip loading info for physical files
                break;

            default:
                if (ai == null)
                {
                    baseImageEditor.Tree = new TreeProvider(MembershipContext.AuthenticatedUser);

                    // If using workflow then get versioned attachment
                    if (VersionHistoryID != 0)
                    {
                        AttachmentHistoryInfo attachmentVersion = VersionManager.GetAttachmentVersion(VersionHistoryID, attachmentGuid);
                        if (attachmentVersion != null)
                        {
                            // Create new attachment object
                            ai = new AttachmentInfo(attachmentVersion.Generalized.DataClass);
                            if (ai != null)
                            {
                                AttachmentHistoryID = attachmentVersion.AttachmentHistoryID;
                                ai.AttachmentVersionHistoryID = VersionHistoryID;
                            }
                        }
                    }
                    // Else get file without binary data
                    else
                    {
                        ai = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(attachmentGuid, CurrentSiteName);
                    }
                }
                break;
        }
    }
        private static string GetDefaultAttachmentFileName(AttachmentInfo attachment)
        {
            if (!attachment.FileName.EndsWith(".zip"))
                return attachment.FileName;

            // remove ".zip"
            return attachment.FileName + "/" + attachment.FileName.Substring(0, attachment.FileName.Length - 4);
        }
    /// <summary>
    /// Gets the new output file object.
    /// </summary>
    /// <param name="ai">AttachmentInfo</param>
    /// <param name="data">Output file data</param>
    public CMSOutputFile NewOutputFile(AttachmentInfo ai, byte[] data)
    {
        CMSOutputFile file = new CMSOutputFile(ai, data);

        file.Watermark = Watermark;
        file.WatermarkPosition = WatermarkPosition;

        return file;
    }
        protected void btnAddAttachment_Click(object sender, EventArgs e)
        {
            string url = ctlAttachment.Url;

            //if (!url.StartsWith("FileID="))//当前没有选择有效文件,直接返回
            //{
            //    return;
            //}
            if (string.IsNullOrEmpty(url))//当前没有选择有效文件,直接返回
            {
                return;
            }
            AttachmentInfo objAttachment = new AttachmentInfo();

            objAttachment.FilePath = ctlAttachment.FullUrl;
            objAttachment.VideoId = VideoId;
            AttachmentController.Add(objAttachment);
            BindAttachmentList();

        }
 /// <summary>
 /// Returns the output data dependency based on the given attachment record.
 /// </summary>
 /// <param name="ai">Attachment object</param>
 protected CacheDependency GetOutputDataDependency(AttachmentInfo ai)
 {
     return (ai == null) ? null : CacheHelper.GetCacheDependency(AttachmentInfoProvider.GetDependencyCacheKeys(ai));
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (dsAttachments == null)
        {
            StopProcessing = true;
        }
        Visible = !StopProcessing;

        if (StopProcessing)
        {
            if (dsAttachments != null)
            {
                dsAttachments.StopProcessing = true;
            }
            if (newAttachmentElem != null)
            {
                newAttachmentElem.StopProcessing = true;
            }
            // Do nothing
        }
        else
        {
            // Register script for tooltips
            if (ShowTooltip)
            {
                ScriptHelper.RegisterTooltip(Page);
            }

            // Ensure info message
            if ((Request["__EVENTTARGET"] == hdnPostback.ClientID) || Request["__EVENTTARGET"] == hdnFullPostback.ClientID)
            {
                string action = Request["__EVENTARGUMENT"];

                switch (action)
                {
                    case "insert":
                        lblInfo.Text = GetString("attach.inserted");
                        break;

                    case "update":
                        lblInfo.Text = GetString("attach.updated");
                        break;

                    case "delete":
                        lblInfo.Text = GetString("attach.deleted");
                        break;

                    default:
                        if (action != "")
                        {
                            UpdateEditParameters(action);
                        }
                        break;
                }
            }

            #region "Scripts"

            // Refresh script
            string script = String.Format(@"
        function RefreshUpdatePanel_{0}(hiddenFieldID, action) {{
           var hiddenField = document.getElementById(hiddenFieldID);
           if (hiddenField) {{
           __doPostBack(hiddenFieldID, action);
           }}
        }}
        function FullRefresh(hiddenFieldID, action) {{
           if(PassiveRefresh != null)
           {{
           PassiveRefresh();
           }}

           var hiddenField = document.getElementById(hiddenFieldID);
           if (hiddenField) {{
           __doPostBack(hiddenFieldID, action);
           }}
        }}
        function FullPageRefresh_{0}(guid) {{
           if(PassiveRefresh != null)
           {{
           PassiveRefresh();
           }}

           var hiddenField = document.getElementById('{1}');if (hiddenField) {{
           __doPostBack('{1}', 'refresh|' + guid);}}
        }}
        function InitRefresh_{0}(msg, fullRefresh, refreshTree, action)
        {{
        if((msg != null) && (msg != '')){{
        alert(msg); action='error';
        }}
        {3}
        if(fullRefresh){{
        FullRefresh('{1}', action);
        }}
        else {{
        RefreshUpdatePanel_{0}('{2}', action);
        }}
        }}
        function DeleteConfirmation() {{
        return confirm({4});;
        }}
        ", ClientID, hdnFullPostback.ClientID, hdnPostback.ClientID, (ActualNode != null ? "if (window.RefreshTree && fullRefresh) { RefreshTree(" + ActualNode.NodeParentID + ", " + ActualNode.NodeID + "); }" : string.Empty), ScriptHelper.GetString(GetString("attach.deleteconfirmation")));

            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "AttachmentScripts_" + ClientID, ScriptHelper.GetScript(script));

            // Register dialog script
            ScriptHelper.RegisterDialogScript(Page);

            // Register jQuery script for thumbnails updating
            ScriptHelper.RegisterJQuery(Page);

            #endregion

            // Initialize button for adding attachments
            newAttachmentElem.ImageUrl = ResolveUrl(GetImageUrl("Design/Controls/DirectUploader/upload_new.png"));
            newAttachmentElem.ImageWidth = 16;
            newAttachmentElem.ImageHeight = 16;
            newAttachmentElem.SourceType = MediaSourceEnum.DocumentAttachments;
            newAttachmentElem.DocumentID = DocumentID;
            newAttachmentElem.NodeParentNodeID = NodeParentNodeID;
            newAttachmentElem.NodeClassName = NodeClassName;
            newAttachmentElem.ResizeToWidth = ResizeToWidth;
            newAttachmentElem.ResizeToHeight = ResizeToHeight;
            newAttachmentElem.ResizeToMaxSideSize = ResizeToMaxSideSize;
            newAttachmentElem.AttachmentGroupGUID = GroupGUID;
            newAttachmentElem.FormGUID = FormGUID;
            newAttachmentElem.AllowedExtensions = AllowedExtensions;
            newAttachmentElem.ParentElemID = ClientID;
            newAttachmentElem.ForceLoad = true;
            newAttachmentElem.InnerDivHtml = GetString("attach.newattachment");
            newAttachmentElem.InnerDivClass = InnerDivClass;
            newAttachmentElem.InnerLoadingDivHtml = GetString("attach.loading");
            newAttachmentElem.InnerLoadingDivClass = InnerLoadingDivClass;
            newAttachmentElem.IsLiveSite = IsLiveSite;
            newAttachmentElem.CheckPermissions = CheckPermissions;
            lblDisabled.CssClass = InnerDivClass + "Disabled";

            imgDisabled.ImageUrl = ResolveUrl(GetImageUrl("Design/Controls/DirectUploader/upload_newdisabled.png"));

            // Grid initialization
            gridAttachments.OnExternalDataBound += gridAttachments_OnExternalDataBound;
            gridAttachments.OnDataReload += gridAttachments_OnDataReload;
            gridAttachments.OnAction += gridAttachments_OnAction;
            gridAttachments.OnBeforeDataReload += gridAttachments_OnBeforeDataReload;
            gridAttachments.ZeroRowsText = GetString("general.nodatafound");
            gridAttachments.IsLiveSite = IsLiveSite;
            gridAttachments.ShowActionsMenu = true;
            gridAttachments.Columns = "AttachmentID, AttachmentGUID, AttachmentImageWidth, AttachmentImageHeight, AttachmentExtension, AttachmentName, AttachmentSize, AttachmentOrder, AttachmentTitle, AttachmentDescription";

            AttachmentInfo ai = new AttachmentInfo();
            gridAttachments.AllColumns = SqlHelperClass.MergeColumns(ai.ColumnNames.ToArray());

            pnlGrid.Attributes.Add("style", "margin-top: 5px;");
        }
    }
        protected void btnAddAttachment_Click(object sender, EventArgs e)
        {

            string url = UserInfo.IsInRole(PortalSettings.AdministratorRoleName) ? ctlAttachment.Url : ctlUserAttachment.Url;

            if (url == "")//当前没有选择任何文件,直接返回
            {
                return;
            }
            FileController fc = new FileController();
            DotNetNuke.Services.FileSystem.FileInfo fi = new DotNetNuke.Services.FileSystem.FileInfo();
            DotNetNuke.Entities.Portals.PortalController ctlPortal = new DotNetNuke.Entities.Portals.PortalController();
            DotNetNuke.Entities.Portals.PortalInfo pi = ctlPortal.GetPortal(PortalId);

            AttachmentInfo ai = new AttachmentInfo();

            if (url.StartsWith("FileID="))
            {
                fi = GetFileInfoById(url);

                if (fi != null && System.IO.File.Exists(fi.PhysicalPath))
                {
                    ai.FilePath = DotNetNuke.Common.Globals.ApplicationPath + "/" + pi.HomeDirectory + "/" + fi.Folder + fi.FileName;

                }
            }
            List<AttachmentInfo> list = AttachmentList;
            if (list == null)
            {
                list = new List<AttachmentInfo>();

            }
            ai.Id = list.Count;//累加Id

            list.Add(ai);
            AttachmentList = list;
            gvAttachment.DataSource = AttachmentList;
            gvAttachment.DataBind();
        }
    public override void ReloadData(bool forceReload)
    {
        Visible = !StopProcessing;
        if (StopProcessing)
        {
            dsAttachments.StopProcessing = true;
            newAttachmentElem.StopProcessing = true;
            // Do nothing
        }
        else
        {
            if ((Node != null) && (Node.DocumentID > 0))
            {
                dsAttachments.Path = Node.NodeAliasPath;
                dsAttachments.CultureCode = Node.DocumentCulture;
                dsAttachments.SiteName = SiteInfoProvider.GetSiteName(Node.OriginalNodeSiteID);
            }

            // Get attachment GUID
            attachmentGuid = ValidationHelper.GetGuid(Value, Guid.Empty);
            if (attachmentGuid == Guid.Empty)
            {
                dsAttachments.StopProcessing = true;
            }

            dsAttachments.DocumentVersionHistoryID = VersionHistoryID;
            dsAttachments.AttachmentFormGUID = FormGUID;
            dsAttachments.AttachmentGUID = attachmentGuid;

            // Force reload datasource
            if (forceReload)
            {
                dsAttachments.DataSource = null;
                dsAttachments.DataBind();
            }

            // Ensure right column name (for attachments under workflow)
            if (!DataHelper.DataSourceIsEmpty(dsAttachments.DataSource))
            {
                DataSet ds = (DataSet)dsAttachments.DataSource;
                if (ds != null)
                {
                    DataTable dt = (ds).Tables[0];
                    if (!dt.Columns.Contains("AttachmentFormGUID"))
                    {
                        dt.Columns.Add("AttachmentFormGUID");
                    }

                    // Get inner attachment
                    innerAttachment = new AttachmentInfo(dt.Rows[0]);
                    Value = innerAttachment.AttachmentGUID;
                    hdnAttachName.Value = innerAttachment.AttachmentName;

                    // Check if temporary attachment should be created
                    createTempAttachment = ((DocumentID == 0) && (DocumentID != innerAttachment.AttachmentDocumentID));
                }
            }

            // Initialize button for adding attachments
            newAttachmentElem.SourceType = MediaSourceEnum.Attachment;
            newAttachmentElem.DocumentID = DocumentID;
            newAttachmentElem.NodeParentNodeID = NodeParentNodeID;
            newAttachmentElem.NodeClassName = NodeClassName;
            newAttachmentElem.ResizeToWidth = ResizeToWidth;
            newAttachmentElem.ResizeToHeight = ResizeToHeight;
            newAttachmentElem.ResizeToMaxSideSize = ResizeToMaxSideSize;
            newAttachmentElem.FormGUID = FormGUID;
            newAttachmentElem.AttachmentGUIDColumnName = GUIDColumnName;
            newAttachmentElem.AllowedExtensions = AllowedExtensions;
            newAttachmentElem.ParentElemID = ClientID;
            newAttachmentElem.ForceLoad = true;
            newAttachmentElem.Text = GetString("attach.uploadfile");
            newAttachmentElem.InnerElementClass = InnerDivClass;
            newAttachmentElem.InnerLoadingElementClass = InnerLoadingDivClass;
            newAttachmentElem.IsLiveSite = IsLiveSite;
            newAttachmentElem.IncludeNewItemInfo = true;
            newAttachmentElem.CheckPermissions = CheckPermissions;
            newAttachmentElem.NodeSiteName = SiteName;

            // Bind UniGrid to DataSource
            gridAttachments.DataSource = dsAttachments.DataSource;
            gridAttachments.LoadGridDefinition();
            gridAttachments.ReloadData();
        }
    }
        private void UpdateArticle()
        {
		try{
            ArticleInfo objArticle = new ArticleInfo();
            objArticle.Id = ArticleId;
            objArticle.PortalId = PortalId;
			objArticle.PublishTime = PublishHour.SelectedItem.Text + ":" + PublishMinute.SelectedItem.Text + " " + PublishAMPM.SelectedItem.Text;
            //Normal 
            objArticle.Title = txtTitle.Text;
            objArticle.Author = txtAuthor.Text;
			objArticle.Keywords = txtKeywords.Text;
			
			objArticle.Image = txtImage.Text;
            objArticle.Thumbnail = txtImage.Text;

            /*if (drpThumbnailImage.SelectedItem.Text != "")
            {
                objArticle.Image = "/Portals/"+customTransactions.PortalId+"/" + drpThumbnailImage.SelectedItem.Text;
                objArticle.Thumbnail = "/Portals/"+customTransactions.PortalId+"/" + drpThumbnailImage.SelectedItem.Text;
            }
            else
            {
                objArticle.Image = null;
                objArticle.Thumbnail = null;
            }*/
            //objArticle.TopStoriesImage = "/Portals/0/" + drpTopStoriesPosition.SelectedItem.Text;

			objArticle.TopStoriesImage = null;
			/*
            if (d1.SelectedItem.Text != "")
            {
                objArticle.TopStoriesImage = "/Portals/0/" + d1.SelectedItem.Text;
            }
            else
            {
                objArticle.TopStoriesImage = null;
            }
			*/
            //Add Categories
            objArticle.Categories = RecursiveHelper.GetAspNetTreeCheckList(tvCategory);

            //Add Tags
            objArticle.Tags = "";
            TagInfo objTag = new TagInfo();
            listData.InnerText = "";
            List<int> tagList = new List<int>();
            foreach (ListItem li in CheckBoxList1.Items)
            {
                if (li.Selected)
                {
                    if (listData.InnerText == "")
                    {
                        objTag = TagController.GetByTag(li.Value.Trim());
                        tagList.Add(objTag.Id);
                    }
                }
            }

            var newTaglist = (from p in tagList select p).Distinct();//remove the  repeated tag item.

            foreach (int item in newTaglist)
            {
                objArticle.Tags += item.ToString() + ",";
            }
            objArticle.Tags = Utils.RemoveSeperator(objArticle.Tags, ",");
            //Tags end

            //date
            if ((txtPublishDate.Text != null) && (txtPublishDate.Text != ""))
            {
                objArticle.PublishDate = Convert.ToDateTime(txtPublishDate.Text);
            }
            else
            {
                objArticle.PublishDate = DateTime.Now;
            }
            if (txtExpireDate.Text != "")
            {
                objArticle.ExpireDate = Convert.ToDateTime(txtExpireDate.Text);
            }

            objArticle.ViewRoles = Utils.GetCheckedItems(cblViewRoles, PortalSettings.AdministratorRoleId);
            //Rating
            objArticle.AllowRating = chkAllowRating.Checked;
            objArticle.RatingRoles = Utils.GetCheckedItems(cblRatingRoles, PortalSettings.AdministratorRoleId);

            //Recommend
            objArticle.AllowRecommend = chkAllowRecommend.Checked;
            objArticle.RecommendRoles = Utils.GetCheckedItems(cblRecommendRoles, PortalSettings.AdministratorRoleId);


            //Comment
            objArticle.AllowComment = chkAllowComment.Checked;
            objArticle.CommentRoles = Utils.GetCheckedItems(cblCommentRoles, PortalSettings.AdministratorRoleId);
            objArticle.AutoAuthComment = chkAutoAuthComment.Checked;
            //Download roles
            objArticle.DownloadRoles = Utils.GetCheckedItems(cblDownloadRoles, PortalSettings.AdministratorRoleId);

            objArticle.Summary = LocalUtils.RemoveAllHtmlTags(txtSummary.Text);
            objArticle.Article = Editor1.Text.Replace("src=&quot;Portals", "src=&quot;/Portals");
            objArticle.UserId = UserId;
            objArticle.Authed = chkPublish.Checked;
            //Now processing attachment
            int newArticleId = -1;
			objBusinessLogic.ArticleID = ArticleId;
            objBusinessLogic.IsPagingEnable = chkPaging.Checked;
            //Page.ClientScript.RegisterStartupScript(this.GetType(), 			 
            //"mKey","alert("+ArticleController.Get(ArticleId).ToString()+")" , true);       

			
            if (ArticleId == -1)
            {                
                newArticleId = ArticleController.Add(objArticle);                
                ArticleId = newArticleId;
				objBusinessLogic.ArticleID = newArticleId;
                objBusinessLogic.UpdateExtraFieldArticle();
            }
            else
            {
                ArticleController.Update(objArticle);
                newArticleId = ArticleId;
				objBusinessLogic.UpdateExtraFieldArticle();
                AttachmentController.DeleteByArticle(ArticleId); //delete attachment first.
            }
            AttachmentInfo ai = new AttachmentInfo();
            foreach (AttachmentInfo item in AttachmentList)
            {
                ai.ArticleId = newArticleId;
                ai.FilePath = item.FilePath;
                AttachmentController.Add(ai);
            }
            //Reset all 
            //ArticleId = -1;
            AttachmentList = new List<AttachmentInfo>();
            gvAttachment.DataSource = AttachmentList;
			
            gvAttachment.DataBind();
			}
			
			catch(Exception Ex)
			{
						Response.Write(Ex.ToString());
			}
        }
Beispiel #42
0
 protected Attachment()
 {
     attachment = new AttachmentInfo();
 }