Beispiel #1
0
        public ActionResult Upload(FormCollection formCollection)
        {
            foreach (string item in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
                if (file.ContentLength > 0)
                {
                    ImageHelper myHelper = new ImageHelper();
                    ImageModel image = myHelper.SaveImageToServer(file);

                    if (image.Error)
                    {
                        // show user friendly error in view
                        ViewBag.Error = image.ErrorMsg;
                    }
                    else
                    {
                        ViewBag.ImagePath = "/Images/"+image.FileName;
                    }
                }
                else
                    ViewBag.Error = "Please select an image";
            }

            return View();
        }
Beispiel #2
0
    // Use this for initialization
    void Start()
    {
        //Image foo = (Image)GameObject.Find("Image_0");
        for (var i = 0; i < 6; i++)
        {
            mSlideHelpers[i] = new ImageHelper();
        }

        mSlides[0] = transform.FindChild("Image_0").gameObject.GetComponent<Image>();
        mSlides[1] = transform.FindChild("Image_1").gameObject.GetComponent<Image>();
        mSlides[2] = transform.FindChild("Image_2").gameObject.GetComponent<Image>();
        mSlides[3] = transform.FindChild("Image_3").gameObject.GetComponent<Image>();
        mSlides[4] = transform.FindChild("Image_4").gameObject.GetComponent<Image>();
        mSlides[5] = transform.FindChild("Image_5").gameObject.GetComponent<Image>();
        mButton = transform.FindChild("Button").gameObject.GetComponent<Button>();

        fadeout[0] = transform.FindChild("Image_fadout").gameObject.GetComponent<Image>();
        fadeout[0].color = new Color(0, 0, 0, 0);
        fadeout[0].transform.position = new Vector3(-1000000,0,0);
        float cur = 0.0f;
        float step = 3.5f;
        mSlideHelpers[0].mStart = cur;
        cur += 3.5f;
        mSlideHelpers[0].mEnd = cur;

        mSlideHelpers[1].mStart = cur;
        cur += step+0.5f;
        mSlideHelpers[1].mEnd = cur;

        mSlideHelpers[2].mStart = cur;
        cur += step + 0.5f;
        mSlideHelpers[2].mEnd = cur;

        mSlideHelpers[3].mStart = cur;
        cur += step;
        mSlideHelpers[3].mEnd = cur;

        mSlideHelpers[4].mStart = cur;
        cur += step;
        mSlideHelpers[4].mEnd = cur;

        mSlideHelpers[5].mStart = cur;
        cur += step-1.0f;
        mSlideHelpers[5].mEnd = cur;
        mButtonStart = cur-1.0f;
        //Vector3 temp = new Vector3(-1000.0f, 0, 0);
        //mButton.transform.position += temp;
        mButton.interactable = false;
        Color c = mButton.image.color;
        c.a = 0.0f;
        mButton.image.color = c;
    }
        public void SupportedImageTest()
        {
            //Test with unsupported extension
            ImageHelper testIH1 = new ImageHelper();
            ImageModel test1 = new ImageModel { Error = false};
            string unsupported = ".avi";
            test1 = testIH1.SupportedImage(test1, unsupported);
            Assert.IsTrue(test1.Error);

            //Test with supported extension
            ImageHelper testIH2 = new ImageHelper();
            ImageModel test2 = new ImageModel { Error = false };
            string supported = ".gif";
            test2 = testIH2.SupportedImage(test2, supported);
            Assert.IsFalse(test2.Error);
        }
Beispiel #4
0
        public ActionResult GetImg()
        {
            string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Content/wolf.jpg");
            var srcImage = Image.FromFile(imageFile);

            ImageHelper helper = new ImageHelper(srcImage);



            Image image = helper.CreateThumbnail(new Size(200, 200));

            //var destImg = ImageHelper.OvalImage(image);

            using (var streak = new MemoryStream())
            {
                image.Save(streak, ImageFormat.Png);
                return File(streak.ToArray(), "image/png");
            }
        }
Beispiel #5
0
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;

            Response.ContentType = "text/plain";

            string action = Request.QueryString["action"];

            if (string.IsNullOrEmpty(action))
            { 
                
            
            }
            else if (action.Trim().ToLower().Equals("validatealert"))
            {
                //是否提醒
                Resource obj = new Resource();
                string userId = Request.QueryString["userId"];
                string isSuperAdmin=Request.QueryString["isSuperAdmin"];

                if (!string.IsNullOrEmpty(userId))
                {
                    if(string.IsNullOrEmpty(isSuperAdmin))
                    {
                        isSuperAdmin="0";
                    }

                    if (obj.IsAlertAdmin(new Guid(userId),isSuperAdmin))
                    {
                        Response.Write("1"); //有新的图片等待审核
                        Response.End();
                    }
                    else
                    {
                        Response.Write("0"); //没有需要审核的图片
                        Response.End();
                    }



                }
                Response.Write("0"); //不用提醒
                Response.End();
            }
            else if (action.Trim().ToLower().Equals("delbatch"))
            { 
                //批量删除

                string itemIds = Request.Form["itemIds"];
                if (string.IsNullOrEmpty(itemIds))
                {
                    Response.Write("0"); //参数错误
                    Response.End();
                    
                }
                itemIds = itemIds.TrimEnd(";".ToCharArray());

                string userId = Request.QueryString["userId"];

                string[] arrId = itemIds.Split(";".ToCharArray());
                foreach (string id in arrId)
                {
                    //删除的图片要记录一下

                    byte[] buffer;

                    ResourceEntity re = null;
                    Resource r = new Resource();
                    re = r.GetResourceInfoByItemId(id);
                    
                    string ItemSerialNum = "";
                    string ImageType = "";
                    string str = "";//判断170图片或者400图片有没有被删除

                    ItemSerialNum = re.ItemSerialNum;
                    //ItemSerialNum = lb_ItemSerialNum.Text;
                    //ImageType = lb_ImageType.Text;
                    //bool isValidate = QJVRMS.Business.ImageStorageClass.DeleteImageStorage(new Guid(this.Hidden_ItemId.Value));

                    bool isValidate = Resource.DeleteResource(re.ItemId);
                    string attachmentFolder = string.Empty;

                    string sourceFolder = string.Empty;
                    string attachmentsFolder = string.Empty;
                    if (re.ResourceType.ToLower().Equals("image"))
                    {
                        string _170Folder;
                        string _400Folder;

                        ImageType obj = new ImageType();
                        
                        try
                        {
                            
                            //记录图片
                            
                            string img = obj.GetPreviewPath(re.FolderName, re.ServerFileName, "170");
                            ImageHelper objImgHelper = new ImageHelper(img);
                            objImgHelper.Resize(80);
                            using (MemoryStream ms = new MemoryStream())
                            {
                                objImgHelper.GetImage().Save(ms, ImageFormat.Jpeg);
                                buffer = ms.ToArray();
                            }
                            objImgHelper.Dispose();



                            //记录日志
                            if (!string.IsNullOrEmpty(userId))
                            {
                                User objUser = new MemberShipManager().GetUser(new Guid(userId));
                                if (objUser != null)
                                {

                                    //日志,所有的删除,只记录一次
                                    LogEntity model = new LogEntity();
                                    model.id = Guid.NewGuid();
                                    model.userId = objUser.UserId;
                                    model.userName = objUser.UserLoginName;
                                    model.EventType = ((int)LogType.DeleteResource).ToString();
                                    model.EventResult = "成功";
                                    model.EventContent = "图片序号:"+re.ItemSerialNum;
                                    model.IP = HttpContext.Current.Request.UserHostAddress;
                                    model.AddDate = DateTime.Now;
                                    new Logs().Add(model);

                                    r.SaveDeletedImage(model.id, buffer);
                                }

                            }


                            File.Delete(obj.GetSourcePath(re.FolderName, re.ServerFileName));
                            attachmentsFolder = obj.SourcePaths[obj.PathNumber].Trim();
                            File.Delete(obj.GetPreviewPath(re.FolderName, re.ServerFileName, "170"));
                            File.Delete(obj.GetPreviewPath(re.FolderName, re.ServerFileName, "400"));



                        }
                        catch { }
                    }
                    else if (re.ResourceType.ToLower().Equals("video"))
                    {
                        string _previewPolder = CommonInfo.VideoPreviewPath;

                        VideoType obj = new VideoType();
                        
                        try
                        {
                            File.Delete(obj.GetSourcePath(string.Empty, re.ServerFileName));
                            attachmentsFolder = obj.SourcePaths[obj.PathNumber].Trim();
                            File.Delete(obj.GetPreviewPath(re.FolderName, re.ServerFileName, "flv"));
                            File.Delete(obj.GetPreviewPath(re.FolderName, re.ServerFileName, "image"));
                            File.Delete(obj.GetPreviewPath(re.FolderName, re.ServerFileName, "smallflv"));
                        }
                        catch
                        {

                        }
                    }

                    //sourceFolder = Path.Combine(sourceFolder, CurrentUser.UserLoginName);
                    //sourceFolder = Path.Combine(sourceFolder, WebUI.UIBiz.CommonInfo.AttachFolder);

                    #region 删除物理文件 by ciqq 2010-4-2
                   
                    //删除所有的附件
                    //string sourceFolder = Path.Combine(WebUI.UIBiz.CommonInfo.ImageRootPath, this.hiFolder.Value);

                    //根据资源ID获得所有的附件

                    DataTable dt = Resource.GetAttachList(new Guid(id));

                    //dt.Columns.Add("fileNamefileLength");

                    //foreach (DataRow dr in dt.Rows)
                    //{
                    //    dr["fileNamefileLength"] = dr["filename"].ToString() + " ( " + Tool.toFileSize(Convert.ToInt64(dr["fileLength"].ToString())) + " ) ";

                    //}

                    //this.attList.DataSource = dt;
                    //this.attList.DataBind();


                    string fileName = "";
                    attachmentsFolder = Path.Combine(attachmentsFolder, re.FolderName);
                    attachmentsFolder = Path.Combine(attachmentsFolder, UIBiz.CommonInfo.AttachFolder);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //fileName = this.attList.DataKeys[i].Values[1].ToString();
                        fileName = dt.Rows[i]["filename"].ToString();
                        fileName = Path.Combine(attachmentsFolder, fileName);
                        try
                        {
                            File.Delete(fileName);
                        }
                        catch (Exception ex)
                        {
                            LogWriter.WriteExceptionLog(ex);
                        }
                    }                   
                    #endregion
                }


                

                Response.Write("0"); //不用提醒
                Response.End();


                
              
                
            }


        }
Beispiel #6
0
        public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode)
        {
            int       pixelSize = GetFieldValueAsInt(FieldType.PIXEL_SIZE);
            Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert);

            if (pixelSize <= 1 || rect.Width == 0 || rect.Height == 0)
            {
                // Nothing to do
                return;
            }
            if (rect.Width < pixelSize)
            {
                pixelSize = rect.Width;
            }
            if (rect.Height < pixelSize)
            {
                pixelSize = rect.Height;
            }
            using (IFastBitmap dest = FastBitmap.CreateCloneOf(applyBitmap, rect))
            {
                using (IFastBitmap src = FastBitmap.Create(applyBitmap, rect))
                {
                    List <Color> colors        = new List <Color>();
                    int          halbPixelSize = pixelSize / 2;
                    for (int y = src.Top - halbPixelSize; y < src.Bottom + halbPixelSize; y = y + pixelSize)
                    {
                        for (int x = src.Left - halbPixelSize; x <= src.Right + halbPixelSize; x = x + pixelSize)
                        {
                            colors.Clear();
                            for (int yy = y; yy < y + pixelSize; yy++)
                            {
                                if (yy >= src.Top && yy < src.Bottom)
                                {
                                    for (int xx = x; xx < x + pixelSize; xx++)
                                    {
                                        if (xx >= src.Left && xx < src.Right)
                                        {
                                            colors.Add(src.GetColorAt(xx, yy));
                                        }
                                    }
                                }
                            }
                            Color currentAvgColor = Colors.Mix(colors);
                            for (int yy = y; yy <= y + pixelSize; yy++)
                            {
                                if (yy >= src.Top && yy < src.Bottom)
                                {
                                    for (int xx = x; xx <= x + pixelSize; xx++)
                                    {
                                        if (xx >= src.Left && xx < src.Right)
                                        {
                                            dest.SetColorAt(xx, yy, currentAvgColor);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                dest.DrawTo(graphics, rect.Location);
            }
        }
Beispiel #7
0
        public static unsafe Texture2D CreateFromStreamUnsynchronized(RenderContext renderContext, Stream stream)
        {
            using var image = Image.Load <Rgba32>(stream);
            image.Mutate(x => x.Flip(FlipMode.Vertical));

            var texture = new Texture2D(renderContext)
            {
                _width  = image.Width,
                _height = image.Height,
            };

            var span = ImageHelper.GetPixelSpan(image);
            int size = span.Length * sizeof(Rgba32);

            fixed(void *data = &MemoryMarshal.GetReference(span))
            {
                var start = new IntPtr(data);

                using var pixelBuffer = PixelBuffer.Create <Rgba32>(renderContext, size, true, true);

                GLHandle prevPixelBuffer = (GLHandle)GL.GetInteger(GetPName.PixelUnpackBufferBinding);

                GL.BindBuffer(BufferTarget.PixelUnpackBuffer, pixelBuffer.Handle);

                // When we load assets asynchronously, using SubData to set the data will cause the main thread
                // to wait for the GL call to complete, so we use a PBO and fill it with a mapped memory range to
                // prevent OpenGL synchronization from causing frame drops on the main thread.

                IntPtr pixelPointer = GL.MapBufferRange(BufferTarget.PixelUnpackBuffer,
                                                        IntPtr.Zero,
                                                        size,
                                                        BufferAccessMask.MapWriteBit
                                                        | BufferAccessMask.MapUnsynchronizedBit
                                                        | BufferAccessMask.MapInvalidateRangeBit);

                if (pixelPointer == IntPtr.Zero)
                {
                    throw new Exception("Could not map PixelUnbackBuffer range.");
                }

                // We send the data to mapped memory in multiple batches instead of one large one for the same
                // reason.

                int       remaining = size;
                const int step      = 2048;

                while (remaining > 0)
                {
                    int   currentStep = Math.Min(remaining, step);
                    int   point       = size - remaining;
                    void *dest        = (void *)IntPtr.Add(pixelPointer, point);
                    void *src         = (void *)IntPtr.Add(start, point);
                    Unsafe.CopyBlock(dest, src, (uint)currentStep);

                    remaining -= step;
                }

                GL.UnmapBuffer(BufferTarget.PixelUnpackBuffer);

                if (GLInfo.HasDirectStateAccess)
                {
                    GL.TextureStorage2D(texture.Handle,
                                        1,
                                        SizedInternalFormat.Rgba8,
                                        texture._width,
                                        texture._height);

                    GL.TextureSubImage2D(texture.Handle,
                                         0,
                                         0,
                                         0,
                                         texture._width,
                                         texture._height,
                                         PixelFormat.Rgba,
                                         PixelType.UnsignedByte,
                                         IntPtr.Zero);

                    GL.GenerateTextureMipmap(texture.Handle);
                }
                else
                {
                    var previousTexture = renderContext.GetCurrentTexture(0);

                    renderContext.BindTexture2D(0, texture);

                    GL.TexImage2D(TextureTarget.Texture2D,
                                  0,
                                  PixelInternalFormat.Rgba,
                                  texture._width,
                                  texture._height,
                                  0,
                                  PixelFormat.Rgba,
                                  PixelType.UnsignedByte,
                                  IntPtr.Zero);

                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);

                    if (previousTexture != null)
                    {
                        previousTexture.Bind(0, renderContext);
                    }
                    else
                    {
                        renderContext.UnbindTexture2D(0);
                    }
                }

                GL.BindBuffer(BufferTarget.PixelUnpackBuffer, prevPixelBuffer);
            }

            texture.SetDefaultTextureParameters(renderContext);

            GL.Finish();

            return(texture);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register tooltip script
        ScriptHelper.RegisterTooltip(Page);
        // Register wopener script
        ScriptHelper.RegisterWOpenerScript(Page);
        // Register only numbers script
        ScriptHelper.RegisterOnlyNumbersScript(Page);
        // Register script file
        ScriptHelper.RegisterScriptFile(Page, ResolveUrl("~/CMSAdminControls/ImageEditor/BaseImageEditor.js"));

        RegisterTrimScript();

        if (LoadImageType != null)
        {
            LoadImageType();
        }

        RegisterResizeIFrameScripts();

        if (!URLHelper.IsPostback())
        {
            // Display image if available data
            if (imageType != ImageHelper.ImageTypeEnum.None)
            {
                if (InitializeProperties != null)
                {
                    InitializeProperties();
                }

                if (!LoadingFailed)
                {
                    currentFormat = imgHelper.ImageFormatToString();
                }
            }

            // Create first version on first load (original)
            if (ImgHelper != null)
            {
                CreateVersion(ImgHelper.SourceData);
            }
        }
        else
        {
            // Load current version to edit
            tempFile = TempFileInfoProvider.GetTempFileInfo(InstanceGUID, CurrentVersion);
            if (tempFile != null)
            {
                tempFile.Generalized.EnsureBinaryData();
                ImgHelper     = new ImageHelper(tempFile.FileBinary);
                currentFormat = imgHelper.ImageFormatToString();
            }

            if (!IsUndoRedoPossible() && (InitializeProperties != null))
            {
                InitializeProperties();
            }

            if (!LoadingFailed && (imgHelper != null))
            {
                currentFormat = imgHelper.ImageFormatToString();
            }
        }

        InitializeStrings(!RequestHelper.IsPostBack());
        InitializeFields();

        if (!URLHelper.IsPostback())
        {
            // Initialize labels depending on image type in parent control
            if (InitializeLabels != null)
            {
                InitializeLabels(true);
            }
        }

        // Show tab 'Properties'
        if (ValidationHelper.GetBoolean(hdnShowProperties.Value, false))
        {
            ScriptHelper.RegisterStartupScript(this, typeof(string), "ShowProperties", ScriptHelper.GetScript("ShowProperties(true, '" + hdnShowProperties.ClientID + "');"));
        }

        if (!IsPreview)
        {
            // Enable or disable meta data editor
            metaDataEditor.Enabled = Enabled;
        }
    }
        /// <summary>
        /// Loads the data to the object.
        /// </summary>
        /// <param name="data">New data</param>
        /// <param name="am">Attachment manager</param>
        public void LoadData()
        {
            if (SharePointFilePath == null)
            {
                throw new Exception("[CMSOutputSharePointFile.LoadData]: Cannot load data to the file object, the SharePoint information missing.");
            }

            // Get data
            mOutputData = GetSPDocument();

            if (mOutputData != null)
            {
                // If is image
                if (ImageHelper.IsMimeImage(MimeType))
                {
                    // Resize image if parameters set
                    if ((MaxSideSize > 0) || (Width > 0) || (Height > 0))
                    {
                        ImageHelper imgHelper = new ImageHelper(mOutputData);

                        // Original dimensions
                        int originalWidth = imgHelper.ImageWidth;
                        int originalHeight = imgHelper.ImageHeight;

                        // Resize
                        int[] dim = imgHelper.EnsureImageDimensions(Width, Height, MaxSideSize);

                        if ((dim[0] != originalWidth) || (dim[1] != originalHeight))
                        {
                            // Get altered data
                            mOutputData = imgHelper.GetResizedImageData(dim[0], dim[1], ImageHelper.DefaultQuality);

                            Resized = true;
                        }
                    }
                }
            }

            mDataLoaded = true;
        }
Beispiel #10
0
 private static string GetFileName(int id, string mime, string suffix)
 {
     return(string.Format("{0}{1}{2}", id, suffix, ImageHelper.GetExtensionFromMime(mime)));
 }
Beispiel #11
0
        /// <summary>
        /// Provides operations necessary to create and store new metafile.
        /// </summary>
        /// <param name="args">Upload arguments.</param>
        /// <param name="context">HttpContext instance.</param>
        private void HandleMetafileUpload(UploaderHelper args, HttpContext context)
        {
            MetaFileInfo mfi = null;

            try
            {
                // Check the allowed extensions
                args.IsExtensionAllowed();

                if (args.IsInsertMode)
                {
                    // Create new metafile info
                    mfi = new MetaFileInfo(args.FilePath, args.MetaFileArgs.ObjectID, args.MetaFileArgs.ObjectType, args.MetaFileArgs.Category);
                    mfi.MetaFileSiteID = args.MetaFileArgs.SiteID;
                }
                else
                {
                    if (args.MetaFileArgs.MetaFileID > 0)
                    {
                        mfi = MetaFileInfoProvider.GetMetaFileInfo(args.MetaFileArgs.MetaFileID);
                    }
                    else
                    {
                        DataSet ds = MetaFileInfoProvider.GetMetaFilesWithoutBinary(args.MetaFileArgs.ObjectID, args.MetaFileArgs.ObjectType, args.MetaFileArgs.Category, null, null);
                        if (!DataHelper.DataSourceIsEmpty(ds))
                        {
                            mfi = new MetaFileInfo(ds.Tables[0].Rows[0]);
                        }
                    }

                    if (mfi != null)
                    {
                        FileInfo fileInfo = FileInfo.New(args.FilePath);
                        // Init the MetaFile data
                        mfi.MetaFileName      = URLHelper.GetSafeFileName(fileInfo.Name, null);
                        mfi.MetaFileExtension = fileInfo.Extension;

                        FileStream file = fileInfo.OpenRead();
                        mfi.MetaFileSize     = Convert.ToInt32(fileInfo.Length);
                        mfi.MetaFileMimeType = MimeTypeHelper.GetMimetype(mfi.MetaFileExtension);
                        mfi.InputStream      = file;

                        // Set image properties
                        if (ImageHelper.IsImage(mfi.MetaFileExtension))
                        {
                            ImageHelper ih = new ImageHelper(mfi.MetaFileBinary);
                            mfi.MetaFileImageHeight = ih.ImageHeight;
                            mfi.MetaFileImageWidth  = ih.ImageWidth;
                        }
                    }
                }

                if (mfi != null)
                {
                    MetaFileInfoProvider.SetMetaFileInfo(mfi);
                }
            }
            catch (Exception ex)
            {
                args.Message = ex.Message;
            }
            finally
            {
                if (String.IsNullOrEmpty(args.Message))
                {
                    if (!string.IsNullOrEmpty(args.AfterSaveJavascript))
                    {
                        args.AfterScript = String.Format(@"
                        if (window.{0} != null) {{
                            window.{0}()
                        }} else if ((window.parent != null) && (window.parent.{0} != null)) {{
                            window.parent.{0}() 
                        }}", args.AfterSaveJavascript);
                    }
                    else
                    {
                        args.AfterScript = String.Format(@"
                        if (window.InitRefresh_{0})
                        {{
                            window.InitRefresh_{0}('{1}', false, false, {2});
                        }}
                        else {{ 
                            if ('{1}' != '') {{
                                alert('{1}');
                            }}
                        }}", args.ParentElementID, ScriptHelper.GetString(args.Message.Trim(), false), mfi.MetaFileID);
                    }
                }
                else
                {
                    args.AfterScript += ScriptHelper.GetAlertScript(args.Message, false);
                }

                args.AddEventTargetPostbackReference();
                context.Response.Write(args.AfterScript);
                context.Response.Flush();
            }
        }
    /// <summary>
    /// Creates new version of image.
    /// </summary>
    /// <param name="data">Image data</param>
    /// <param name="name">File name</param>
    /// <param name="title">File title</param>
    /// <param name="description">File description</param>
    public void CreateVersion(byte[] data, string name, string title, string description)
    {
        if (IsUndoRedoPossible())
        {
            // If current
            if ((CurrentVersion) >= MaxVersionsCount)
            {
                ShowError(GetString("img.errors.maxversion"));
                LoadingFailed = true;
            }
            else if (ImgHelper != null)
            {
                try
                {
                    // Set the imagehelper to new data
                    ImgHelper = new ImageHelper(data);
                    CurrentVersion++;

                    // Save new file version
                    TempFileInfo tfi = new TempFileInfo();
                    tfi.FileDirectory = "ImageEditor";
                    tfi.FileBinary = data;
                    tfi.FileParentGUID = InstanceGUID;
                    tfi.FileExtension = "." + currentFormat;
                    tfi.FileName = name;
                    tfi.FileTitle = title;
                    tfi.FileDescription = description;
                    tfi.FileNumber = CurrentVersion;
                    tfi.FileMimeType = "image/" + (currentFormat == "jpg" ? "jpeg" : currentFormat);
                    tfi.FileImageWidth = ImgHelper.ImageWidth;
                    tfi.FileImageHeight = ImgHelper.ImageHeight;
                    tfi.FileSize = ImgHelper.SourceData.Length;
                    tfi.FileSiteName = SiteContext.CurrentSiteName;

                    tempFile = tfi;

                    SetScriptProperties(true);

                    // Delete all next temporary files before creating new
                    TempFileInfoProvider.DeleteTempFiles(TempFileInfoProvider.IMAGE_EDITOR_FOLDER, InstanceGUID, CurrentVersion - 1, MaxVersionsCount);

                    // Save new temporary file
                    TempFileInfoProvider.SetTempFileInfo(tfi);

                    // Oldest version is always current if creating new version
                    OldestVersion = CurrentVersion;
                }
                catch (Exception ex)
                {
                    ShowError(GetString("img.errors.processing"),ex.Message);
                    EventLogProvider.LogException("Image editor", "LOAD", ex);
                    LoadingFailed = true;
                }
            }
        }
        else
        {
            if (SaveImage != null)
            {
                string extension = "." + currentFormat;
                string mimetype = "image/" + (currentFormat == "jpg" ? "jpeg" : currentFormat);

                ImgHelper.LoadImage(data);

                SaveImage(name, extension, mimetype, title, description, data, ImgHelper.ImageWidth, ImgHelper.ImageHeight);
            }
        }
    }
Beispiel #13
0
        public MainForm()
        {
            InitializeComponent();

            //textEdit4.ReadOnly = true;
            textEdit4.Properties.Appearance.Image                    = global::TestDEControls.Properties.Resources.save_16x16;
            textEdit4.Properties.Appearance.Options.UseImage         = true;
            textEdit4.Properties.AppearanceFocused.Image             = global::TestDEControls.Properties.Resources.save_16x16;
            textEdit4.Properties.AppearanceFocused.Options.UseImage  = true;
            textEdit4.Properties.AppearanceDisabled.Image            = global::TestDEControls.Properties.Resources.save_16x16;
            textEdit4.Properties.AppearanceDisabled.Options.UseImage = true;
            textEdit4.Properties.AppearanceReadOnly.Image            = global::TestDEControls.Properties.Resources.save_16x16;
            textEdit4.Properties.AppearanceReadOnly.Options.UseImage = true;

            btnSet.Visible = false;

            _boolVictim4CheckBox = _boolVictim4ToggleSwitch = true;
            _defaultBooleanVictim4ToggleSwitch = DefaultBoolean.True;
            _stringVictim = "123456789012";

            _textEdit3Binding = textEdit3.DataBindings.Add("EditValue", this, "StringVictim", true, DataSourceUpdateMode.OnPropertyChanged);
            _textEdit3Binding.BindingComplete += TextEdit3BindingBindingComplete;
            _textEdit3Binding.Format          += TextEdit3BindingFormat;
            _textEdit3Binding.Parse           += TextEdit3BindingParse;
            textEdit3.CustomDisplayText       += TextEdit3CustomDisplayText;

            //tabControl.SelectedTabPage = tabPageButtons;

            lookUpEdit1.Properties.DataSource    = GetDataTable();
            lookUpEdit1.Properties.ValueMember   = "id";
            lookUpEdit1.Properties.DisplayMember = "Name";
            lookUpEdit1.Properties.Columns.Clear();
            lookUpEdit1.Properties.Columns.Add(new LookUpColumnInfo("Name"));
            lookUpEdit1.Properties.ShowHeader = false;
            lookUpEdit1.Properties.ShowFooter = false;

            lookUpEdit2.Properties.DataSource    = GetListStubsWithIdBool();
            lookUpEdit2.Properties.ValueMember   = "Id";
            lookUpEdit2.Properties.DisplayMember = "Name";
            lookUpEdit2.Properties.Columns.Clear();
            lookUpEdit2.Properties.Columns.Add(new LookUpColumnInfo("Name"));
            lookUpEdit2.Properties.ShowHeader = false;
            lookUpEdit2.Properties.ShowFooter = false;
            //lookUpEdit2.DataBindings.Add("EditValue", editObjectWithBool, "FBool", false, DataSourceUpdateMode.OnPropertyChanged);
            lookUpEdit2.DataBindings.Add("EditValue", editObjectWithNullableBool, "FBool", false, DataSourceUpdateMode.OnPropertyChanged);

            lookUpEdit3.Properties.DataSource    = GetListStubsWithIdInt();
            lookUpEdit3.Properties.ValueMember   = "Id";
            lookUpEdit3.Properties.DisplayMember = "Name";
            lookUpEdit3.Properties.Columns.Clear();
            lookUpEdit3.Properties.Columns.Add(new LookUpColumnInfo("Name"));
            lookUpEdit3.Properties.ShowHeader = false;
            lookUpEdit3.Properties.ShowFooter = false;
            lookUpEdit3.DataBindings.Add("EditValue", editObjectWithInt, "FInt", false, DataSourceUpdateMode.OnPropertyChanged);

            lookUpEdit4.Properties.DataSource    = GetListStubsWithIdDevExpressDefaultBoolean();
            lookUpEdit4.Properties.ValueMember   = "Id";
            lookUpEdit4.Properties.DisplayMember = "Name";
            lookUpEdit4.Properties.Columns.Clear();
            lookUpEdit4.Properties.Columns.Add(new LookUpColumnInfo("Name"));
            lookUpEdit4.Properties.ShowHeader = false;
            lookUpEdit4.Properties.ShowFooter = false;
            lookUpEdit4.DataBindings.Add("EditValue", editObjectWithDevExpressDefaultBoolean, "FBool", false, DataSourceUpdateMode.OnPropertyChanged);

            textEdit1.Properties.Mask.MaskType     = MaskType.RegEx;
            textEdit1.Properties.Mask.EditMask     = "a{1,3}";
            textEdit1.Properties.Mask.AutoComplete = AutoCompleteType.None;

            gridControl1.DataSource = GetDataTable();

            var repositoryItemComboBox = new RepositoryItemComboBox();

            repositoryItemComboBox.Items.AddRange(new[] { 1, 2, 3 });

            // https://documentation.devexpress.com/#WindowsForms/DevExpressXtraEditorsHyperLinkEdit_OpenLinktopic
            var repositoryItemHyperLinkEdit = new RepositoryItemHyperLinkEdit();

            repositoryItemHyperLinkEdit.SingleClick = true;
            //repositoryItemHyperLinkEdit.ReadOnly = true;
            repositoryItemHyperLinkEdit.TextEditStyle = TextEditStyles.DisableTextEditor;

            var repositoryItemSpinEdit = new RepositoryItemSpinEdit();

            repositoryItemSpinEdit.DisplayFormat.FormatString = "0.###############";
            repositoryItemSpinEdit.DisplayFormat.FormatType   = FormatType.Numeric;
            repositoryItemSpinEdit.Mask.EditMask = "n15";
            repositoryItemSpinEdit.MaxLength     = 30;
            repositoryItemSpinEdit.MaxValue      = 79228162514264.337593543950335m;

            gridControl1.RepositoryItems.Add(repositoryItemComboBox);
            gridControl1.RepositoryItems.Add(repositoryItemHyperLinkEdit);
            gridControl1.RepositoryItems.Add(repositoryItemSpinEdit);
            gridView1.Columns.ColumnByFieldName("Dep").ColumnEdit    = repositoryItemComboBox;
            gridView1.Columns.ColumnByFieldName("Url").ColumnEdit    = repositoryItemHyperLinkEdit;
            gridView1.Columns.ColumnByFieldName("Salary").ColumnEdit = repositoryItemSpinEdit;

            repositoryItemComboBox.EditValueChanging += RepositoryItemComboBoxOnEditValueChanging;
            repositoryItemComboBox.EditValueChanged  += RepositoryItemComboBoxOnEditValueChanged;

            gridView1.CustomRowCellEdit += GridViewOnCustomRowCellEdit;
            //gridView1.OptionsBehavior.Editable = false;
            gridView1.Click += gridViewClick;
            //gridView1.CustomDrawRowIndicator += GridViewCustomDrawRowIndicatorFake;

            checkEdit4.DataBindings.Add("EditValue", this, "BoolVictim4CheckBox", false, DataSourceUpdateMode.OnPropertyChanged);
            //checkEdit4.DataBindings.Add("EditValue", this, "BoolVictim4CheckBox", false, DataSourceUpdateMode.OnValidation);

            //pictureEdit.Enabled = false;
            pictureEdit.ReadOnly                = true;
            pictureEdit.Properties.ReadOnly     = true;
            pictureEdit.Properties.AllowFocused = false;
            //pictureEdit.Properties.ShowMenu = false;

            var assembly  = typeof(PictureMenu).Assembly;
            var imageList = ImageHelper.CreateImageCollectionFromResources("DevExpress.XtraEditors.Images.PictureMenu.png", typeof(PictureMenu).Assembly, new Size(0x10, 0x10), Color.Empty);

            Image img = null;

            try
            {
                img = ResourceImageHelper.CreateBitmapFromResources("DevExpress.XtraEditors.ImageEdit.bmp", typeof(ButtonEdit).Assembly);
                img.Save("ImageEdit.bmp");
                imageList = ImageHelper.CreateImageCollectionFromResources("DevExpress.XtraEditors.Images.Editors.bmp", typeof(PictureMenu).Assembly, new Size(0x10, 0x10), Color.Empty);
                imageList.Images[12].Save("12.bmp");
                //img = (Bitmap)Bitmap.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("DevExpress.XtraEditors.Images.Editors.bmp"));
            }
            catch (Exception)
            {
            }

            comboBoxEdit1.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            comboBoxEdit1.Properties.Items.AddRange(Enumerable.Range(65, 26).Select(item => (object)(new string((char)item, 10))).ToArray());

            //timeEdit1.Properties.ReadOnly = true;
            timeEdit1.Enabled = false;

            listOfAction.Add(GridViewCustomDrawRowIndicatorFake);

            DecimalVictim = 1.123456789010000m;
            //DecimalVictim = 0.00000001m;

            spinEdit1.DataBindings.Add("EditValue", this, "DecimalVictim", false, DataSourceUpdateMode.OnPropertyChanged);
            //spinEdit1.EditValueChanged += SpinEditEditValueChanged;
            //spinEdit1.CustomDisplayText += SpinEditCustomDisplayText;

            toggleSwitch1.DataBindings.Add("EditValue", this, "BoolVictim4ToggleSwitch", false, DataSourceUpdateMode.OnPropertyChanged);
            _toggleSwitch2Binding                  = toggleSwitch2.DataBindings.Add(/*"EditValue"*/ "IsOn", this, "DefaultBooleanVictim4ToggleSwitch", true, DataSourceUpdateMode.OnPropertyChanged);
            _toggleSwitch2Binding.Parse           += ToggleSwitchBindingParse;
            _toggleSwitch2Binding.Format          += ToggleSwitchBindingFormat;
            _toggleSwitch2Binding.BindingComplete += ToggleSwitchBindingBindingComplete;

            buttonEdit1.ReadOnly     = true;
            buttonEdit1.ButtonClick += ButtonEdit1_ButtonClick;
            buttonEdit1.Properties.Buttons[1].Enabled = false;
            buttonEdit1.EditValue = "blah-blah-blah";
        }
        public override Result <Book> Update(Book entity)
        {
            Result <Book> result = Validate(entity, x =>
                                            x.Title,
                                            x => x.Author,
                                            x => x.Approved,
                                            x => x.FreightOption,
                                            x => x.Id);



            var bookId = entity.Id;

            if (!result.Success)
            {
                return(result);
            }

            //buscar o book no banco para obter um objeto para ser re-hidratado
            var savedBook = this._repository.Find(bookId);

            if (savedBook == null)
            {
                throw new ShareBookException(ShareBookException.Error.NotFound);
            }

            //Como o objeto foi buscado diretamente do banco, removi a consulta e tratei diretamente no objeto
            var bookAlreadyApproved = savedBook.Approved;

            if (!bookAlreadyApproved)
            {
                entity.Slug = SetSlugByTitleOrIncremental(entity);
            }


            //imagem eh opcional no update
            if (!string.IsNullOrEmpty(entity.ImageName) && entity.ImageBytes.Length > 0)
            {
                entity.ImageSlug = ImageHelper.FormatImageName(entity.ImageName, savedBook.Slug);
                _uploadService.UploadImage(entity.ImageBytes, savedBook.ImageSlug, "Books");
            }

            //preparar o book para atualização
            savedBook.Author        = entity.Author;
            savedBook.FreightOption = entity.FreightOption;
            savedBook.Approved      = entity.Approved;
            savedBook.Author        = entity.Author;
            savedBook.ImageSlug     = entity.ImageSlug;
            savedBook.Title         = entity.Title;
            savedBook.CategoryId    = entity.CategoryId;
            savedBook.Canceled      = entity.Canceled;

            savedBook.Synopsis       = entity.Synopsis;
            savedBook.TrackingNumber = entity.TrackingNumber;

            if (entity.UserIdFacilitator.HasValue && entity.UserIdFacilitator != Guid.Empty)
            {
                savedBook.UserIdFacilitator = entity.UserIdFacilitator;
            }

            result.Value            = _repository.UpdateAsync(savedBook).Result;
            result.Value.ImageBytes = null;

            // TODO: pedir pro pessoal de front usar o endpoint correto de aprovação.
            if (!bookAlreadyApproved && entity.Approved)
            {
                this.Approve(entity.Id);
            }

            return(result);
        }
Beispiel #15
0
        public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation?orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
        {
            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException("inputPath");
            }
            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException("outputPath");
            }

            var skiaOutputFormat = GetImageFormat(selectedOutputFormat);

            var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
            var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
            var blur         = options.Blur ?? 0;
            var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);

            using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
            {
                if (bitmap == null)
                {
                    throw new Exception(string.Format("Skia unable to read image {0}", inputPath));
                }

                //_logger.Info("Color type {0}", bitmap.Info.ColorType);

                var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
                ImageHelper.SaveImageSize(inputPath, dateModified, originalImageSize);

                if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
                {
                    // Just spit out the original file if all the options are default
                    return(inputPath);
                }

                var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);

                var width  = Convert.ToInt32(Math.Round(newImageSize.Width));
                var height = Convert.ToInt32(Math.Round(newImageSize.Height));

                using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
                {
                    // scale image
                    var resizeMethod = SKBitmapResizeMethod.Lanczos3;

                    bitmap.Resize(resizedBitmap, resizeMethod);

                    // If all we're doing is resizing then we can stop now
                    if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
                    {
                        using (var outputStream = new SKFileWStream(outputPath))
                        {
                            resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
                            return(outputPath);
                        }
                    }

                    // create bitmap to use for canvas drawing
                    using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
                    {
                        // create canvas used to draw into bitmap
                        using (var canvas = new SKCanvas(saveBitmap))
                        {
                            // set background color if present
                            if (hasBackgroundColor)
                            {
                                canvas.Clear(SKColor.Parse(options.BackgroundColor));
                            }

                            // Add blur if option is present
                            if (blur > 0)
                            {
                                using (var paint = new SKPaint())
                                {
                                    // create image from resized bitmap to apply blur
                                    using (var filter = SKImageFilter.CreateBlur(blur, blur))
                                    {
                                        paint.ImageFilter = filter;
                                        canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
                                    }
                                }
                            }
                            else
                            {
                                // draw resized bitmap onto canvas
                                canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
                            }

                            // If foreground layer present then draw
                            if (hasForegroundColor)
                            {
                                Double opacity;
                                if (!Double.TryParse(options.ForegroundLayer, out opacity))
                                {
                                    opacity = .4;
                                }

                                canvas.DrawColor(new SKColor(0, 0, 0, (Byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
                            }

                            if (hasIndicator)
                            {
                                DrawIndicator(canvas, width, height, options);
                            }

                            using (var outputStream = new SKFileWStream(outputPath))
                            {
                                saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
                            }
                        }
                    }
                }
            }
            return(outputPath);
        }
Beispiel #16
0
        private async Task SearchSubmit_ExecuteAsync()
        {
            DisplayErrors.Clear();
            TimeSpan?timeSinceUpdate = DateTime.Now - OracleCatalog.UpdateTime;

            if (timeSinceUpdate == null)
            {
                var yesNoDialog = new YesNoDialogViewModel("Card Catalog must be updated before continuing. Would you like to update the Card Catalog (~65 MB) now?", "Update?");
                if (!(DialogService.ShowDialog(yesNoDialog) ?? false))
                {
                    return;
                }

                await UpdateCatalog_ExecuteAsync();
            }

            if (timeSinceUpdate > TimeSpan.FromDays(7))
            {
                var yesNoDialog = new YesNoDialogViewModel("Card Catalog is out of date, it is recommended you get a new catalog now." +
                                                           "If you don't, cards may not appear in search results or you may receive old " +
                                                           "imagery. Click 'Yes' to update the Card Catalog (~65 MB) now or 'No' use the old catalog.", "Update?");
                if (!(DialogService.ShowDialog(yesNoDialog) ?? false))
                {
                    return;
                }

                await UpdateCatalog_ExecuteAsync();
            }

            DisplayedCards.Clear();
            await Task.Delay(100);

            Reporter.StartBusy();
            Reporter.StartProgress();
            Reporter.Report("Deciphering old one's poem");
            Reporter.StatusReported += BuildingCardsErrors;

            List <SearchLine> lines = DecklistText
                                      .Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)
                                      .Where(s => !string.IsNullOrWhiteSpace(s))
                                      .Select(l => new SearchLine(l))
                                      .ToList();

            for (var i = 0; i < lines.Count; i++)
            {
                List <Card> cards = OracleCatalog.FindExactCard(lines[i].SearchTerm);

                if (!cards.Any())
                {
                    cards.Add(await ScryfallService.GetFuzzyCardAsync(lines[i].SearchTerm, Reporter));
                }

                if (!cards.Any() || cards.Any(c => c == null))
                {
                    Reporter.Report($"[{lines[i].SearchTerm}] returned no results", true);
                    continue;
                }

                Card preferredCard;

                if (cards.Count > 1)
                {
                    var cardChooser = new ChooseCardDialogViewModel(cards, Reporter);
                    await cardChooser.LoadImagesFromCards();

                    if (!(DialogService.ShowDialog(cardChooser) ?? false))
                    {
                        continue;
                    }

                    preferredCard = ArtPreferences.GetPreferredCard(cardChooser.ChosenCard);
                }
                else
                {
                    preferredCard = ArtPreferences.GetPreferredCard(cards.Single());
                }

                if (preferredCard.IsDoubleFaced)
                {
                    BitmapSource frontImage = ImageHelper.LoadBitmap(await ImageCaching.GetImageAsync(preferredCard.CardFaces[0].ImageUris.BorderCrop, Reporter));
                    var          frontVm    = new CardViewModel(Reporter, ArtPreferences, preferredCard, frontImage, lines[i].Quantity, ZoomPercent);

                    BitmapSource backImage = ImageHelper.LoadBitmap(await ImageCaching.GetImageAsync(preferredCard.CardFaces[1].ImageUris.BorderCrop, Reporter));
                    var          backVm    = new CardViewModel(Reporter, ArtPreferences, preferredCard, backImage, lines[i].Quantity, ZoomPercent, false);

                    DisplayedCards.Add(frontVm);
                    await Task.Delay(10);

                    DisplayedCards.Add(backVm);
                    await Task.Delay(10);

                    Reporter.Progress(i, 0, lines.Count - 1);
                }
                else
                {
                    BitmapSource preferredImage = ImageHelper.LoadBitmap(await ImageCaching.GetImageAsync(preferredCard.ImageUris.BorderCrop, Reporter));
                    var          cardVm         = new CardViewModel(Reporter, ArtPreferences, preferredCard, preferredImage, lines[i].Quantity, ZoomPercent);
                    DisplayedCards.Add(cardVm);
                    await Task.Delay(10);

                    Reporter.Progress(i, 0, lines.Count - 1);
                }
            }

            Reporter.StatusReported -= BuildingCardsErrors;
            Reporter.StopBusy();
            Reporter.StopProgress();
        }
Beispiel #17
0
        public DatabasesContextMenu(DatabaseMenuCommandParameters databaseMenuCommandParameters, ExplorerToolWindow parent)
        {
            var dcmd = new DatabasesMenuCommandsHandler(parent);

            // Add 4.0 database menu
            bool ver40IsInstalled = DataConnectionHelper.IsV40Installed();
            bool ver35IsInstalled = DataConnectionHelper.IsV35Installed();

            var addCe4DatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                  dcmd.AddPrivateCe40Database);
            var addCeDatabaseMenuItem = new MenuItem
            {
                Header           = "Add SQL Server Compact 4.0 Connection...",
                Icon             = ImageHelper.GetImageFromResource("../resources/AddConnection_477.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            var pkg = parent.Package as SqlCeToolboxPackage;

            if (pkg != null && pkg.VsSupportsDdex40())
            {
                var addCe40DatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                       dcmd.AddCe40Database);
                addCeDatabaseMenuItem.CommandBindings.Add(addCe40DatabaseCommandBinding);
                addCeDatabaseMenuItem.IsEnabled = ver40IsInstalled;
                Items.Add(addCeDatabaseMenuItem);
            }
            else
            {
                addCeDatabaseMenuItem.CommandBindings.Add(addCe4DatabaseCommandBinding);
                addCeDatabaseMenuItem.IsEnabled = ver40IsInstalled;
                Items.Add(addCeDatabaseMenuItem);
            }

            // Add 3.5 database menu
            var addCe35DatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                   dcmd.AddCe35Database);
            var addCe35DatabaseMenuItem = new MenuItem
            {
                Header           = "Add SQL Server Compact 3.5 Connection...",
                Icon             = ImageHelper.GetImageFromResource("../resources/AddConnection_477.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };

            if (pkg != null && pkg.VsSupportsDdex35())
            {
                addCe35DatabaseMenuItem.CommandBindings.Add(addCe35DatabaseCommandBinding);
                addCe35DatabaseMenuItem.IsEnabled = ver35IsInstalled;
                Items.Add(addCe35DatabaseMenuItem);
            }
            else
            {
                var addCe3511DatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                         dcmd.AddPrivateCe35Database);
                addCe35DatabaseMenuItem.CommandBindings.Add(addCe3511DatabaseCommandBinding);
                addCe35DatabaseMenuItem.IsEnabled = ver35IsInstalled;
                Items.Add(addCe35DatabaseMenuItem);
            }

            // Add SQLite database menu
            var addSqLiteDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                     dcmd.AddSqLiteDatabase);
            var addSqLiteDatabaseMenuItem = new MenuItem
            {
                Header           = "Add SQLite Connection...",
                Icon             = ImageHelper.GetImageFromResource("../resources/AddConnection_477.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };

            addSqLiteDatabaseMenuItem.CommandBindings.Add(addSqLiteDatabaseCommandBinding);
            Items.Add(addSqLiteDatabaseMenuItem);

            // Add from solution
            var addFromSolutionCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                   dcmd.ScanConnections);

            var addFromSolutionMenuItem = new MenuItem
            {
                Header           = "Add Connections from Solution",
                Icon             = ImageHelper.GetImageFromResource("../resources/AddConnection_477.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                ToolTip          = "Scan current Solution for SQL Compact and SQLite files",
                CommandParameter = databaseMenuCommandParameters,
            };

            addFromSolutionMenuItem.CommandBindings.Add(addFromSolutionCommandBinding);
            addFromSolutionMenuItem.IsEnabled = ver40IsInstalled || ver35IsInstalled;
            if (SqlCeToolboxPackage.IsVsExtension)
            {
                Items.Add(addFromSolutionMenuItem);
            }

            // Fix connections
            var fixConnectionsCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                  dcmd.FixConnections);

            var fixConnectionsMenuItem = new MenuItem
            {
                Header           = "Remove broken connections",
                Icon             = ImageHelper.GetImageFromResource("../resources/action_Cancel_16xLG.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                ToolTip          = "Remove invalid connections",
                CommandParameter = databaseMenuCommandParameters,
            };

            fixConnectionsMenuItem.CommandBindings.Add(fixConnectionsCommandBinding);
            Items.Add(fixConnectionsMenuItem);

            Items.Add(new Separator());

            var scriptGraphCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                               dcmd.GenerateServerDgmlFiles);
            var scriptDatabaseGraphMenuItem = new MenuItem
            {
                Header           = "Create SQL Server Database Graph (DGML)...",
                Icon             = ImageHelper.GetImageFromResource("../resources/Diagram_16XLG.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };

            scriptDatabaseGraphMenuItem.CommandBindings.Add(scriptGraphCommandBinding);
            if (SqlCeToolboxPackage.IsVsExtension)
            {
                Items.Add(scriptDatabaseGraphMenuItem);
            }

            var designDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                  dcmd.DesignDatabase);
            var designDatabaseMenuItem = new MenuItem
            {
                Header           = "Database designer (alpha)...",
                Icon             = ImageHelper.GetImageFromResource("../resources/Schema_16xLG.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };

            designDatabaseMenuItem.CommandBindings.Add(designDatabaseCommandBinding);
            Items.Add(designDatabaseMenuItem);
            Items.Add(new Separator());

            var scriptDatabaseRootMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database",
                Icon   = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
            };

            var toolTip = new ToolTip();

            toolTip.Content = "Generate a SQL Server Compact compatible database script from SQL Server 2005+";

            var scriptDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                  dcmd.ScriptServerDatabase);

            var scriptDatabaseSchemaMenuItem = new MenuItem
            {
                Header           = "Script SQL Server Database Schema...",
                Icon             = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip          = toolTip,
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.Schema
            };

            scriptDatabaseSchemaMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaMenuItem);

            var scriptDatabaseDataMenuItem = new MenuItem
            {
                Header           = "Script SQL Server Database Data...",
                Icon             = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip          = toolTip,
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.DataOnly
            };

            scriptDatabaseDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseDataMenuItem);

            var scriptDatabaseSchemaDataMenuItem = new MenuItem
            {
                Header           = "Script SQL Server Database Schema and Data...",
                Icon             = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip          = toolTip,
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaData
            };

            scriptDatabaseSchemaDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataMenuItem);

            var scriptDatabaseSchemaDataSqLiteMenuItem = new MenuItem
            {
                Header           = "Script SQL Server Database Schema and Data for SQLite...",
                Icon             = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip          = toolTip,
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataSQLite
            };

            scriptDatabaseSchemaDataSqLiteMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataSqLiteMenuItem);

            var scriptDatabaseSchemaSqLiteMenuItem = new MenuItem
            {
                Header           = "Script SQL Server Database Schema for SQLite...",
                Icon             = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip          = toolTip,
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaSQLite
            };

            scriptDatabaseSchemaSqLiteMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaSqLiteMenuItem);

            var scriptDatabaseSchemaDataBlobMenuItem = new MenuItem
            {
                Header           = "Script SQL Server Database Schema and Data with BLOBs...",
                ToolTip          = toolTip,
                Icon             = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataBlobs
            };

            scriptDatabaseSchemaDataBlobMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataBlobMenuItem);

            Items.Add(scriptDatabaseRootMenuItem);

            Items.Add(new Separator());

            var exportServerCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                dcmd.ExportServerDatabaseTo40);
            var exportServerMenuItem = new MenuItem
            {
                Header           = "Export SQL Server to SQL Server Compact 4.0...",
                Icon             = ImageHelper.GetImageFromResource("../resources/ExportReportData_10565.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };

            exportServerMenuItem.CommandBindings.Add(exportServerCommandBinding);
            exportServerMenuItem.IsEnabled = (ver40IsInstalled);
            Items.Add(exportServerMenuItem);

            var exportServerToLiteCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                      dcmd.ExportServerDatabaseToSqlite);
            var exportServerToLiteMenuItem = new MenuItem
            {
                Header           = "Export SQL Server to SQLite... (beta)",
                Icon             = ImageHelper.GetImageFromResource("../resources/ExportReportData_10565.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };

            exportServerToLiteMenuItem.CommandBindings.Add(exportServerToLiteCommandBinding);
            Items.Add(exportServerToLiteMenuItem);

            Items.Add(new Separator());

            //TODO Enable in next release
            //var scriptEfDacPacCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
            //    dcmd.GenerateEfPocoFromDacPacInProject);

            //var scriptEfPocoDacPacMenuItem = new MenuItem
            //{
            //    Header = "Add Entity Data Model (Code First from Dacpac) to current Project... (alpha)",
            //    Icon = ImageHelper.GetImageFromResource("../resources/Schema_16xLG.png"),
            //    Command = DatabaseMenuCommands.DatabaseCommand,
            //    CommandParameter = databaseMenuCommandParameters,
            //};
            //scriptEfPocoDacPacMenuItem.CommandBindings.Add(scriptEfDacPacCommandBinding);
            //if (SqlCeToolboxPackage.VsSupportsEf6()) Items.Add(scriptEfPocoDacPacMenuItem);

            var localDatabaseCacheCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                      dcmd.SyncFxGenerateLocalDatabaseCacheCode);
            var localDatabaseCacheMenuItem = new MenuItem
            {
                Header           = "Generate Local Database Cache code...",
                Icon             = ImageHelper.GetImageFromResource("../resources/Synchronize_16xLG.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataBlobs
            };

            localDatabaseCacheMenuItem.CommandBindings.Add(localDatabaseCacheCommandBinding);
            localDatabaseCacheMenuItem.IsEnabled = (ver35IsInstalled && DataConnectionHelper.IsSyncFx21Installed());
            if (SqlCeToolboxPackage.IsVsExtension)
            {
                Items.Add(localDatabaseCacheMenuItem);
            }

            if (SqlCeToolboxPackage.IsVsExtension)
            {
                Items.Add(new Separator());
            }
            var detectDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                  dcmd.CheckCeVersion);

            var versionDetectMenuItem = new MenuItem
            {
                Header           = "Detect SQL Server Compact file version...",
                Icon             = ImageHelper.GetImageFromResource("../resources/Find_5650.png"),
                Command          = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };

            versionDetectMenuItem.CommandBindings.Add(detectDatabaseCommandBinding);
            Items.Add(versionDetectMenuItem);
        }
Beispiel #18
0
    /// <summary>
    /// Edit file event handler.
    /// </summary>
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        // Check 'File modify' permission
        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "filemodify"))
        {
            this.lblErrorEdit.Text = MediaLibraryHelper.GetAccessDeniedMessage("filemodify");
            this.lblErrorEdit.Visible = true;

            SetupFile();
            return;
        }

        FileInfo fi = CMS.IO.FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(CMSContext.CurrentSiteName, this.LibraryInfo.LibraryFolder, this.FilePath));
        if ((fi != null) && (this.LibraryInfo != null))
        {
            if (this.FileInfo != null)
            {

                this.FileInfo.FileModifiedWhen = DateTime.Now;
                // Set media file info
                this.FileInfo.FileSize = fi.Length;
                if (ImageHelper.IsImage(FileInfo.FileExtension))
                {
                    ImageHelper ih = new ImageHelper();
                    ih.LoadImage(File.ReadAllBytes(fi.FullName));
                    this.FileInfo.FileImageWidth = ih.ImageWidth;
                    this.FileInfo.FileImageHeight = ih.ImageHeight;
                }
                this.FileInfo.FileTitle = this.txtEditTitle.Text.Trim();
                this.FileInfo.FileDescription = this.txtEditDescription.Text.Trim();

                // Save
                MediaFileInfoProvider.SetMediaFileInfo(this.FileInfo);

                // Remove old thumbnails
                MediaFileInfoProvider.DeleteMediaFileThumbnails(FileInfo);

                // Inform user on success
                this.lblInfoEdit.Text = GetString("media.refresh.success");
                this.lblInfoEdit.Visible = true;

                this.pnlUpdateEditInfo.Update();

                SetupTexts();

                SetupFile();
                this.pnlUpdateGeneral.Update();

                SetupPreview();
                this.pnlUpdatePreviewDetails.Update();

                SetupEdit();
                this.pnlUpdateFileInfo.Update();

                SetupVersions(false);
                pnlUpdateVersions.Update();

                RaiseOnAction("rehighlightitem", Path.GetFileName(this.FileInfo.FilePath));
            }
        }
    }
Beispiel #19
0
        /// <summary>
        /// Provides operations necessary to create and store new attachment.
        /// </summary>
        /// <param name="args">Upload arguments.</param>
        /// <param name="context">HttpContext instance.</param>
        private void HandleAttachmentUpload(UploaderHelper args, HttpContext context)
        {
            AttachmentInfo newAttachment = null;
            bool           refreshTree   = false;

            try
            {
                args.IsExtensionAllowed();

                // Get existing document
                if (args.AttachmentArgs.DocumentID != 0)
                {
                    node = DocumentHelper.GetDocument(args.AttachmentArgs.DocumentID, TreeProvider);
                    if (node == null)
                    {
                        throw new Exception("Given document doesn't exist!");
                    }
                    else
                    {
                        #region "Check permissions"

                        // For new document
                        if (args.AttachmentArgs.FormGuid != Guid.Empty)
                        {
                            if (args.AttachmentArgs.ParentNodeID == 0)
                            {
                                throw new Exception(ResHelper.GetString("attach.document.parentmissing"));
                            }

                            if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(args.AttachmentArgs.ParentNodeID, args.AttachmentArgs.NodeClassName))
                            {
                                throw new Exception(ResHelper.GetString("attach.actiondenied"));
                            }
                        }
                        // For existing document
                        else if (args.AttachmentArgs.DocumentID > 0)
                        {
                            if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)
                            {
                                throw new Exception(ResHelper.GetString("attach.actiondenied"));
                            }
                        }

                        #endregion


                        args.IsExtensionAllowed();

                        // Check out the document
                        if (AutoCheck && args.IsLastUpload)
                        {
                            // Get current step info
                            WorkflowStepInfo si = WorkflowManager.GetStepInfo(node);
                            if (si != null)
                            {
                                // Decide if full refresh is needed
                                args.FullRefresh = si.StepIsPublished || si.StepIsArchived;
                            }

                            VersionManager.CheckOut(node, node.IsPublished, true);
                        }

                        // Handle field attachment
                        if (args.AttachmentArgs.FieldAttachment)
                        {
                            // Extension of CMS file before saving
                            string oldExtension = node.DocumentType;

                            newAttachment = DocumentHelper.AddAttachment(node, args.AttachmentArgs.AttachmentGuidColumnName, Guid.Empty, Guid.Empty, args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide);
                            DocumentHelper.UpdateDocument(node, TreeProvider);

                            // Different extension
                            if ((oldExtension != null) && !oldExtension.EqualsCSafe(node.DocumentType, true))
                            {
                                refreshTree = true;
                            }
                        }
                        else
                        {
                            // Handle grouped and unsorted attachments
                            if (args.AttachmentArgs.AttachmentGroupGuid != Guid.Empty)
                            {
                                // Grouped attachment
                                newAttachment = DocumentHelper.AddGroupedAttachment(node, args.AttachmentArgs.AttachmentGUID, args.AttachmentArgs.AttachmentGroupGuid, args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide);
                            }
                            else
                            {
                                // Unsorted attachment
                                newAttachment = DocumentHelper.AddUnsortedAttachment(node, args.AttachmentArgs.AttachmentGUID, args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide);
                            }

                            // Log synchronization task if not under workflow
                            if (wi == null)
                            {
                                DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, TreeProvider);
                            }
                        }

                        // Check in the document
                        if (AutoCheck)
                        {
                            VersionManager.CheckIn(node, null, null);
                        }
                    }
                }
                else if (args.AttachmentArgs.FormGuid != Guid.Empty)
                {
                    newAttachment = AttachmentInfoProvider.AddTemporaryAttachment(args.AttachmentArgs.FormGuid, args.AttachmentArgs.AttachmentGuidColumnName, args.AttachmentArgs.AttachmentGUID, args.AttachmentArgs.AttachmentGroupGuid, args.FilePath, CMSContext.CurrentSiteID, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide);
                }

                if (newAttachment == null)
                {
                    throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied.");
                }
            }
            catch (Exception ex)
            {
                // Log the exception
                EventLogProvider.LogException("Content", "UploadAttachment", ex);

                // Store exception message
                args.Message = ex.Message;
            }
            finally
            {
                // Call after save javascript if exists
                if (!string.IsNullOrEmpty(args.AfterSaveJavascript))
                {
                    if ((args.Message == string.Empty) && (newAttachment != null))
                    {
                        string url      = null;
                        string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, CMSContext.CurrentSiteName);
                        if (node != null)
                        {
                            SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                            if (si != null)
                            {
                                url = SettingsKeyProvider.GetBoolValue(si.SiteName + ".CMSUsePermanentURLs") ?
                                      URLHelper.ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName))
                                    : URLHelper.ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(saveName, node.NodeAliasPath));
                            }
                        }
                        else
                        {
                            url = URLHelper.ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName));
                        }

                        Hashtable obj = new Hashtable();
                        if (ImageHelper.IsImage(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.IMG_URL]     = url;
                            obj[DialogParameters.IMG_TOOLTIP] = newAttachment.AttachmentName;
                            obj[DialogParameters.IMG_WIDTH]   = newAttachment.AttachmentImageWidth;
                            obj[DialogParameters.IMG_HEIGHT]  = newAttachment.AttachmentImageHeight;
                        }
                        else if (MediaHelper.IsFlash(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE]  = "flash";
                            obj[DialogParameters.FLASH_URL]    = url;
                            obj[DialogParameters.FLASH_EXT]    = newAttachment.AttachmentExtension;
                            obj[DialogParameters.FLASH_TITLE]  = newAttachment.AttachmentName;
                            obj[DialogParameters.FLASH_WIDTH]  = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.FLASH_HEIGHT] = DEFAULT_OBJECT_HEIGHT;
                        }
                        else if (MediaHelper.IsAudioVideo(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE] = "audiovideo";
                            obj[DialogParameters.AV_URL]      = url;
                            obj[DialogParameters.AV_EXT]      = newAttachment.AttachmentExtension;
                            obj[DialogParameters.AV_WIDTH]    = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.AV_HEIGHT]   = DEFAULT_OBJECT_HEIGHT;
                        }
                        else
                        {
                            obj[DialogParameters.LINK_URL]  = url;
                            obj[DialogParameters.LINK_TEXT] = newAttachment.AttachmentName;
                        }

                        // Calling javascript function with parameters attachments url, name, width, height
                        args.AfterScript += string.Format(@"{5}
                        if (window.{0})
                        {{
                            window.{0}('{1}', '{2}', '{3}', '{4}', obj);
                        }}
                        else if((window.parent != null) && window.parent.{0})
                        {{
                            window.parent.{0}('{1}', '{2}', '{3}', '{4}', obj);
                        }}", args.AfterSaveJavascript, url, newAttachment.AttachmentName, newAttachment.AttachmentImageWidth, newAttachment.AttachmentImageHeight, CMSDialogHelper.GetDialogItem(obj));
                    }
                    else
                    {
                        args.AfterScript += ScriptHelper.GetAlertScript(args.Message, false);
                    }
                }

                // Create attachment info string
                string attachmentInfo = ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (args.IncludeNewItemInfo)) ? String.Format("'{0}', ", newAttachment.AttachmentGUID) : "";

                // Create after script and return it to the silverlight application, this script will be evaluated by the SL application in the end
                args.AfterScript += string.Format(@"
                if (window.InitRefresh_{0})
                {{
                    window.InitRefresh_{0}('{1}', {2}, {3}, {4});
                }}
                else {{ 
                    if ('{1}' != '') {{
                        alert('{1}');
                    }}
                }}",
                                                  args.ParentElementID,
                                                  ScriptHelper.GetString(args.Message.Trim(), false),
                                                  args.FullRefresh.ToString().ToLowerCSafe(),
                                                  refreshTree.ToString().ToLowerCSafe(),
                                                  attachmentInfo + (args.IsInsertMode ? "'insert'" : "'update'"));

                args.AddEventTargetPostbackReference();
                context.Response.Write(args.AfterScript);
                context.Response.Flush();
            }
        }
    /// <summary>
    /// Provides operations necessary to create and store new physical file.
    /// </summary>
    private void HandlePhysicalFilesUpload()
    {
        string message = string.Empty;

        try
        {
            // Check the allowed extensions
            CheckAllowedExtensions();

            // Prepare the file name
            string extension = Path.GetExtension(ucFileUpload.FileName);
            string fileName = TargetFileName;
            if (String.IsNullOrEmpty(fileName))
            {
                fileName = Path.GetFileName(ucFileUpload.FileName);
            }
            else if (!fileName.Contains("."))
            {
                fileName += extension;
            }

            // Prepare the path
            if (String.IsNullOrEmpty(TargetFolderPath))
            {
                TargetFolderPath = "~/";
            }

            string filePath = TargetFolderPath;

            // Try to map virtual and relative path to server
            try
            {
                if (!Path.IsPathRooted(filePath))
                {
                    filePath = Server.MapPath(filePath);
                }
            }
            catch
            {
            }

            filePath = DirectoryHelper.CombinePath(filePath, fileName);

            // Ensure directory
            DirectoryHelper.EnsureDiskPath(filePath, SystemContext.WebApplicationPhysicalPath);

            // Ensure unique file name
            if (String.IsNullOrEmpty(TargetFileName) && File.Exists(filePath))
            {
                int index = 0;
                string basePath = filePath.Substring(0, filePath.Length - extension.Length);
                string newPath = filePath;

                do
                {
                    index++;
                    newPath = basePath + "_" + index + extension;
                } while (File.Exists(newPath));

                filePath = newPath;
            }

            // Upload file
            if (ImageHelper.IsImage(extension) && ((ResizeToHeight > 0) || (ResizeToWidth > 0) || (ResizeToMaxSideSize > 0)))
            {
                byte[] data = ucFileUpload.FileBytes;

                // Resize the image
                ImageHelper img = new ImageHelper(data);
                int[] newSize = ImageHelper.EnsureImageDimensions(ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize, img.ImageWidth, img.ImageHeight);
                if ((newSize[0] != img.ImageWidth) || (newSize[1] != img.ImageHeight))
                {
                    data = img.GetResizedImageData(newSize[0], newSize[1]);
                }

                // Write to file
                File.WriteAllBytes(filePath, data);
            }
            else
            {
                File.WriteAllBytes(filePath, ucFileUpload.FileBytes);
            }
        }
        catch (Exception ex)
        {
            // Log the exception
            EventLogProvider.LogException("Uploader", "UploadPhysicalFile", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;
            if (!String.IsNullOrEmpty(message))
            {
                afterSaveScript = "setTimeout(\"alert(" + ScriptHelper.GetString(ScriptHelper.GetString(message), false) + ")\", 1);";
            }
            else
            {
                if (!string.IsNullOrEmpty(AfterSaveJavascript))
                {
                    afterSaveScript = String.Format(
        @"
        if (window.{0} != null) {{
        window.{0}(files)
        }} else if ((window.parent != null) && (window.parent.{0} != null)) {{
        window.parent.{0}(files)
        }}
        ",
                        AfterSaveJavascript
                    );
                }
                else
                {
                    afterSaveScript += "if ((window.parent != null) && (/parentelemid=" + ParentElemID + "/i.test(window.location.href)) && (window.parent.InitRefresh_" + ParentElemID + " != null)){window.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", false, false);}";
                }
            }

            afterSaveScript = ScriptHelper.GetScript(afterSaveScript);

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript);
        }
    }
 public override ImageAttributes Apply()
 {
     return(ImageHelper.GetImageAttributesFromEffect(KnownEffectType.GrayScaleGreen));
 }
    protected void imgRefresh_Click(object sender, EventArgs e)
    {
        if (plcMediaType.Visible)
        {
            MediaSource source = CMSDialogHelper.GetMediaData(txtUrl.Text, null);
            if ((source == null) || (source.MediaType == MediaTypeEnum.Unknown))
            {
                Properties.ItemNotSystem = true;

                // Try get source type from URL extension
                int index = txtUrl.Text.LastIndexOfCSafe('.');
                if (index > 0)
                {
                    string ext = txtUrl.Text.Substring(index);
                    if (ext.Contains("?"))
                    {
                        ext = URLHelper.RemoveQuery(ext);
                    }
                    if (source == null)
                    {
                        source = new MediaSource();
                    }
                    source.Extension = ext;
                    if (source.MediaType == MediaTypeEnum.Image)
                    {
                        try
                        {
                            // Get the data
                            WebClient wc = new WebClient();
                            byte[] img = wc.DownloadData(txtUrl.Text.Trim());
                            ImageHelper ih = new ImageHelper(img);
                            if (ih.ImageWidth > 0)
                            {
                                mWidth = ih.ImageWidth;
                            }
                            if (ih.ImageHeight > 0)
                            {
                                mHeight = ih.ImageHeight;
                            }
                            wc.Dispose();
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        source.MediaWidth = 300;
                        source.MediaHeight = 200;
                    }
                }
            }
            else
            {
                Properties.ItemNotSystem = false;
            }

            if (source != null)
            {
                // Set default dimensions when not specified
                if ((mWidth == 0) && (mHeight == 0))
                {
                    mWidth = source.MediaWidth;
                    mHeight = source.MediaHeight;
                }
                switch (source.MediaType)
                {
                    case MediaTypeEnum.Image:
                        drpMediaType.SelectedValue = "image";
                        break;

                    case MediaTypeEnum.AudioVideo:
                        drpMediaType.SelectedValue = "av";
                        break;

                    case MediaTypeEnum.Flash:
                        drpMediaType.SelectedValue = "flash";
                        break;
                    default:
                        drpMediaType.SelectedValue = "";
                        plcInfo.Visible = true;
                        lblInfo.ResourceString = "dialogs.web.selecttype";
                        break;
                }
            }

            if (source != null)
            {
                SetLastType(source.MediaType);
            }

            ShowProperties();
        }
    }
Beispiel #23
0
        public IEnumerable <ImageFragment> SplitTo(int xParts, int yParts, bool appendOverrides)
        {
            var size = ImageHelper.GetDimensions(FilePath);
            var fw   = size.Width / xParts;
            var fh   = size.Height / yParts;

            for (int xi = 0; xi < xParts; xi++)
            {
                int x = xi * fw;
                for (int yi = 0; yi < yParts; yi++)
                {
                    int y      = yi * fh;
                    int width  = fw;
                    int height = fh;

                    if ((x + width) > size.Width)
                    {
                        width = size.Width - x;
                    }
                    if ((y + height) > size.Height)
                    {
                        height = size.Height - y;
                    }

                    var annotations = new List <Annotation>();
                    foreach (var annotation in Annotations)
                    {
                        var a = Yacobi(annotation, size.Width, size.Height, x, y, width, height);
                        if (a != null)
                        {
                            annotations.Add(a);
                        }
                    }
                    yield return(new ImageFragment
                    {
                        Annotations = annotations,
                        FilePath = this.FilePath,
                        X = x,
                        Y = y,
                        Height = height,
                        Width = width
                    });
                }
            }

            if (appendOverrides)
            {
                for (int xi = 0; xi < xParts - 1; xi++)
                {
                    int x = xi * fw / 2;
                    for (int yi = 0; yi < yParts; yi++)
                    {
                        int y      = yi * fh;
                        int width  = fw;
                        int height = fh;

                        if ((x + width) > size.Width)
                        {
                            width = size.Width - x;
                        }
                        if ((y + height) > size.Height)
                        {
                            height = size.Height - y;
                        }

                        var annotations = new List <Annotation>();
                        foreach (var annotation in Annotations)
                        {
                            var a = Yacobi(annotation, size.Width, size.Height, x, y, width, height);
                            if (a != null)
                            {
                                annotations.Add(a);
                            }
                        }
                        yield return(new ImageFragment
                        {
                            Annotations = annotations,
                            FilePath = this.FilePath,
                            X = x,
                            Y = y,
                            Height = height,
                            Width = width
                        });
                    }

                    for (int yi = 0; yi < yParts - 1; yi++)
                    {
                        int y      = yi * fh / 2;
                        int width  = fw;
                        int height = fh;

                        if ((x + width) > size.Width)
                        {
                            width = size.Width - x;
                        }
                        if ((y + height) > size.Height)
                        {
                            height = size.Height - y;
                        }
                        var annotations = new List <Annotation>();
                        foreach (var annotation in Annotations)
                        {
                            var a = Yacobi(annotation, size.Width, size.Height, x, y, width, height);
                            if (a != null)
                            {
                                annotations.Add(a);
                            }
                        }
                        yield return(new ImageFragment
                        {
                            Annotations = annotations,
                            FilePath = this.FilePath,
                            X = x,
                            Y = y,
                            Height = height,
                            Width = width
                        });
                    }
                }
            }
        }
    /// <summary>
    /// Refreshes file information.
    /// </summary>
    private void RefreshFileInformation()
    {
        // Check 'File modify' permission
        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "filemodify"))
        {
            ShowError(MediaLibraryHelper.GetAccessDeniedMessage("filemodify"));

            SetupFile();
            return;
        }

        FileInfo fi = CMS.IO.FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(SiteContext.CurrentSiteName, LibraryInfo.LibraryFolder, FilePath));
        if ((fi != null) && (LibraryInfo != null))
        {
            if (FileInfo != null)
            {
                FileInfo.FileModifiedWhen = DateTime.Now;
                // Set media file info
                FileInfo.FileSize = fi.Length;
                if (ImageHelper.IsImage(FileInfo.FileExtension))
                {
                    ImageHelper ih = new ImageHelper();
                    ih.LoadImage(File.ReadAllBytes(fi.FullName));
                    FileInfo.FileImageWidth = ih.ImageWidth;
                    FileInfo.FileImageHeight = ih.ImageHeight;
                }
                FileInfo.FileTitle = txtEditTitle.Text.Trim();
                FileInfo.FileDescription = txtEditDescription.Text.Trim();

                // Save
                MediaFileInfoProvider.SetMediaFileInfo(FileInfo);

                // Remove old thumbnails
                MediaFileInfoProvider.DeleteMediaFileThumbnails(FileInfo);

                // Inform user on success
                ShowConfirmation(GetString("media.refresh.success"));

                SetupFile();
                pnlUpdateGeneral.Update();

                SetupPreview();
                pnlUpdatePreviewDetails.Update();

                SetupEdit();
                pnlUpdateFileInfo.Update();

                SetupVersions();
                pnlUpdateVersions.Update();

                RaiseOnAction("rehighlightitem", Path.GetFileName(FileInfo.FilePath));
            }
        }
    }
Beispiel #25
0
        private void button1_Click(object sender, EventArgs e)
        {
            List <string> DeptNameList = new List <string>()
            {
                "一师", "一团", "二团"
            };
            DataTable dt = GetData(DeptNameList);

            Workbook  workbook  = new Workbook();
            Worksheet worksheet = workbook.Worksheets[0];

            worksheet.PageSetup.Orientation = PageOrientationType.Landscape; //横向打印
            worksheet.PageSetup.Zoom        = 100;                           //以100%的缩放模式打开
            worksheet.PageSetup.PaperSize   = PaperSizeType.PaperA4;

            Range range; Cell cell;
            int   colSpan = 4 + DeptNameList.Count * 2;

            range = worksheet.Cells.CreateRange(0, 0, 1, colSpan);
            range.Merge();
            range.RowHeight = 20;
            range.SetStyle(CreateTitleStyle(workbook));
            cell = range[0, 0];
            cell.PutValue("患病情况统计");

            range = worksheet.Cells.CreateRange(1, 0, 1, colSpan);
            range.Merge();
            range.RowHeight = 15;
            cell            = range[0, 0];
            cell.PutValue("所选部别范围内,总计有1000名人员,查询统计结果如下:");

            range = worksheet.Cells.CreateRange(2, 0, 1, colSpan);
            range.Merge();
            range.RowHeight = 15;
            cell            = range[0, 0];
            cell.PutValue("自2007-1-1开始到现在,统计共有500人有患病史,累计900人次,患病情况如下表:");

            #region 生成报表头部表格
            Style headStyle   = CreateStyle(workbook, true);
            Style normalStyle = CreateStyle(workbook, false);
            int   startRow    = 4;
            range = worksheet.Cells.CreateRange(startRow, 0, 2, 1);
            range.Merge();
            range.SetStyle(headStyle);
            cell = range[0, 0];
            cell.PutValue("序号");
            cell.SetStyle(headStyle);

            range = worksheet.Cells.CreateRange(startRow, 1, 2, 1);
            range.Merge();
            range.SetStyle(headStyle);
            range.ColumnWidth = 40;
            cell = range[0, 0];
            cell.PutValue("疾病名称");
            cell.SetStyle(headStyle);

            int startCol = 2;
            foreach (string deptName in DeptNameList)
            {
                range = worksheet.Cells.CreateRange(startRow, startCol, 1, 2);
                range.Merge();
                range.SetStyle(headStyle);
                cell = range[0, 0];
                cell.PutValue(deptName);

                cell = worksheet.Cells[startRow + 1, startCol];
                cell.PutValue("人次");
                cell.SetStyle(headStyle);
                cell = worksheet.Cells[startRow + 1, startCol + 1];
                cell.PutValue("百分比");
                cell.SetStyle(headStyle);

                startCol += 2;
            }

            range = worksheet.Cells.CreateRange(startRow, startCol, 1, 2);
            range.Merge();
            range.SetStyle(headStyle);
            cell = range[0, 0];
            cell.PutValue("合计");

            cell = worksheet.Cells[startRow + 1, startCol];
            cell.PutValue("人次");
            cell.SetStyle(headStyle);
            cell = worksheet.Cells[startRow + 1, startCol + 1];
            cell.PutValue("百分比");
            cell.SetStyle(headStyle);
            #endregion

            //写入数据到Excel
            startRow = startRow + 2;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                startCol = 0;
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    DataRow dr = dt.Rows[i];
                    cell = worksheet.Cells[startRow, startCol];
                    cell.PutValue(dr[j]);
                    cell.SetStyle(normalStyle);

                    startCol++;
                }
                startRow++;
            }

            //写入图注
            startRow += 1;//跳过1行
            range     = worksheet.Cells.CreateRange(startRow++, 0, 1, colSpan);
            range.Merge();
            range.RowHeight = 15;
            cell            = range[0, 0];
            cell.PutValue("以柱状图展示如下:");

            //插入图片到Excel里面
            byte[] bytes = ImageHelper.ImageToBytes(this.pictureBox1.Image);
            using (MemoryStream stream = new MemoryStream(bytes))
            {
                worksheet.Pictures.Add(startRow, 0, stream);
            }

            //Save the excel file.
            string saveFile = FileDialogHelper.SaveExcel("rangecells.xls", "C:\\");
            if (!string.IsNullOrEmpty(saveFile))
            {
                workbook.Save(saveFile);
                if (MessageDxUtil.ShowYesNoAndTips("保存成功,是否打开文件?") == System.Windows.Forms.DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(saveFile);
                }
            }
        }
Beispiel #26
0
        public static unsafe Texture2D CreateFromStream(RenderContext renderContext, Stream stream)
        {
            using Image <Rgba32> image = Image.Load <Rgba32>(stream);
            image.Mutate(x => x.Flip(FlipMode.Vertical));

            var texture = new Texture2D(renderContext)
            {
                _width  = image.Width,
                _height = image.Height,
            };

            fixed(void *data = &MemoryMarshal.GetReference(ImageHelper.GetPixelSpan(image)))
            {
                if (GLInfo.HasDirectStateAccess)
                {
                    GL.TextureStorage2D(texture.Handle,
                                        1,
                                        SizedInternalFormat.Rgba8,
                                        texture._width,
                                        texture._height);

                    GL.TextureSubImage2D(texture.Handle,
                                         0,
                                         0,
                                         0,
                                         texture._width,
                                         texture._height,
                                         PixelFormat.Rgba,
                                         PixelType.UnsignedByte,
                                         new IntPtr(data));

                    GL.GenerateTextureMipmap(texture.Handle);
                }
                else
                {
                    var previousTexture = renderContext.GetCurrentTexture(0);

                    renderContext.BindTexture2D(0, texture);

                    GL.TexImage2D(TextureTarget.Texture2D,
                                  0,
                                  PixelInternalFormat.Rgba,
                                  texture._width,
                                  texture._height,
                                  0,
                                  PixelFormat.Rgba,
                                  PixelType.UnsignedByte,
                                  new IntPtr(data));

                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);

                    if (previousTexture != null)
                    {
                        previousTexture.Bind(0, renderContext);
                    }
                    else
                    {
                        renderContext.UnbindTexture2D(0);
                    }
                }
            }

            texture.SetDefaultTextureParameters(renderContext);

            return(texture);
        }
Beispiel #27
0
 private void SetImages()
 {
     ImageHelper.RoundPhoto(userPhoto);
 }
    /// <summary>
    /// Creates new version of image.
    /// </summary>
    /// <param name="data">Image data</param>
    /// <param name="name">File name</param>
    /// <param name="title">File title</param>
    /// <param name="description">File description</param>
    public void CreateVersion(byte[] data, string name, string title, string description)
    {
        if (IsUndoRedoPossible())
        {
            // If current
            if ((CurrentVersion) >= MaxVersionsCount)
            {
                ShowError(GetString("img.errors.maxversion"));
                LoadingFailed = true;
            }
            else if (ImgHelper != null)
            {
                try
                {
                    // Set the imagehelper to new data
                    ImgHelper = new ImageHelper(data);
                    CurrentVersion++;

                    // Save new file version
                    TempFileInfo tfi = new TempFileInfo();
                    tfi.FileDirectory   = "ImageEditor";
                    tfi.FileBinary      = data;
                    tfi.FileParentGUID  = InstanceGUID;
                    tfi.FileExtension   = "." + currentFormat;
                    tfi.FileName        = name;
                    tfi.FileTitle       = title;
                    tfi.FileDescription = description;
                    tfi.FileNumber      = CurrentVersion;
                    tfi.FileMimeType    = "image/" + (currentFormat == "jpg" ? "jpeg" : currentFormat);
                    tfi.FileImageWidth  = ImgHelper.ImageWidth;
                    tfi.FileImageHeight = ImgHelper.ImageHeight;
                    tfi.FileSize        = ImgHelper.SourceData.Length;
                    tfi.FileSiteName    = SiteContext.CurrentSiteName;

                    tempFile = tfi;

                    SetScriptProperties(true);

                    // Delete all next temporary files before creating new
                    TempFileInfoProvider.DeleteTempFiles(TempFileInfoProvider.IMAGE_EDITOR_FOLDER, InstanceGUID, CurrentVersion - 1, MaxVersionsCount);

                    // Save new temporary file
                    TempFileInfoProvider.SetTempFileInfo(tfi);

                    // Oldest version is always current if creating new version
                    OldestVersion = CurrentVersion;
                }
                catch (Exception ex)
                {
                    ShowError(GetString("img.errors.processing"), ex.Message);
                    EventLogProvider.LogException("Image editor", "LOAD", ex);
                    LoadingFailed = true;
                }
            }
        }
        else
        {
            if (SaveImage != null)
            {
                string extension = "." + currentFormat;
                string mimetype  = "image/" + (currentFormat == "jpg" ? "jpeg" : currentFormat);

                ImgHelper.LoadImage(data);

                SaveImage(name, extension, mimetype, title, description, data, ImgHelper.ImageWidth, ImgHelper.ImageHeight);
            }
        }
    }
Beispiel #29
0
        /// <summary>
        /// Resizes and crops the image.
        /// </summary>
        /// <param name="mediaImage">The image.</param>
        /// <param name="request">The request.</param>
        private MemoryStream ResizeAndCropImage(MediaImage mediaImage, ImageViewModel request)
        {
            int?x1 = request.CropCoordX1;
            int?x2 = request.CropCoordX2;
            int?y1 = request.CropCoordY1;
            int?y2 = request.CropCoordY2;

            var cropped = true;

            if ((x1 <= 0 && y1 <= 0 && ((x2 >= mediaImage.OriginalWidth && y2 >= mediaImage.OriginalHeight) || (x2 <= 0 && y2 <= 0))))
            {
                x1      = y1 = x2 = y2 = null;
                cropped = false;
            }

            var newWidth  = request.ImageWidth;
            var newHeight = request.ImageHeight;
            var resized   = (newWidth != mediaImage.OriginalWidth || newHeight != mediaImage.OriginalHeight);

            var memoryStream = new MemoryStream();

            var hasChanges = (mediaImage.Width != newWidth ||
                              mediaImage.Height != newHeight ||
                              x1 != mediaImage.CropCoordX1 ||
                              x2 != mediaImage.CropCoordX2 ||
                              y1 != mediaImage.CropCoordY1 ||
                              y2 != mediaImage.CropCoordY2);

            if (hasChanges)
            {
                DownloadResponse downloadResponse = StorageService.DownloadObject(mediaImage.OriginalUri);
                var dimensionsCalculator          = new ImageDimensionsCalculator(newWidth, newHeight, mediaImage.OriginalWidth, mediaImage.OriginalHeight, x1, x2, y1, y2);
                using (var image = Image.FromStream(downloadResponse.ResponseStream))
                {
                    var destination = image;
                    var codec       = ImageHelper.GetImageCodec(destination);

                    if (resized)
                    {
                        destination = ImageHelper.Resize(destination, new Size {
                            Width = newWidth, Height = newHeight
                        });
                    }

                    if (cropped)
                    {
                        var width   = dimensionsCalculator.ResizedCroppedWidth;
                        var heigth  = dimensionsCalculator.ResizedCroppedHeight;
                        var cropX12 = dimensionsCalculator.ResizedCropCoordX1.Value;
                        var cropY12 = dimensionsCalculator.ResizedCropCoordY1.Value;

                        Rectangle rec = new Rectangle(cropX12, cropY12, width, heigth);
                        destination = ImageHelper.Crop(destination, rec);
                    }

                    destination.Save(memoryStream, codec, null);
                    mediaImage.Size = memoryStream.Length;
                }
            }

            mediaImage.CropCoordX1 = x1;
            mediaImage.CropCoordY1 = y1;
            mediaImage.CropCoordX2 = x2;
            mediaImage.CropCoordY2 = y2;

            mediaImage.Width  = newWidth;
            mediaImage.Height = newHeight;

            return(memoryStream);
        }
Beispiel #30
0
 public ActionResult CenterAlterFace()
 {
     if (Request.HttpMethod == "GET")
     {
         return(View());
     }
     else
     {
         var avatarFile = Request.Files["AvatarFile"];
         if (avatarFile != null)
         {
             if (!System.IO.Directory.Exists(MyPath.TempPath))
             {
                 System.IO.Directory.CreateDirectory(MyPath.TempPath);
             }
             var avatarName = avatarFile.FileName;
             var avatarExt  = Path.GetExtension(avatarName);
             //保存原图
             var savePath = Path.Combine(MyPath.TempPath, avatarName);
             if (WebHelper.saveUploadFile(avatarFile, savePath, Config.ImgExtensions.Split('*'), this.pathConfig.dic["avatar"].FileSize))
             {
                 if (!System.IO.Directory.Exists(this.pathConfig.dic["avatar"].DirPath))
                 {
                     System.IO.Directory.CreateDirectory(this.pathConfig.dic["avatar"].DirPath);
                 }
                 //缩略图路径
                 var thumbPath = Path.Combine(this.pathConfig.dic["avatar"].DirPath, "Avatar_" + LoginUser.User_Id + avatarExt);
                 //生成头像缩略图
                 ImageHelper.MakeThumbnailImage(savePath, thumbPath, 48, 48, "HW");
                 LoginUser.Avatar = this.pathConfig.dic["avatar"].WebPath + "/" + "Avatar_" + LoginUser.User_Id + avatarExt;
                 System.IO.File.Delete(savePath);
                 Model.Sys.User u = this.userService.Find(LoginUser.User_Id);
                 if (base.Config.DefaultAvatar != u.Avatar)
                 {
                     string _syspath = HIO.SysPathParse(MyPath.AppPath, u.Avatar, true);
                     try
                     {
                         System.IO.File.Delete(_syspath);
                     }
                     catch (Exception e)
                     {
                         HIO.WriteLog(e);
                     }
                 }
                 u.Avatar = LoginUser.Avatar;
                 this.userService.Update(u);
                 return(Json(new ResultModel {
                     pass = true, msg = "上传成功", append = new { url = LoginUser.Avatar }
                 }));
             }
             else
             {
                 return(Json(new ResultModel {
                     msg = "上传文件错误,注意文件大小" + this.pathConfig.dic["avatar"].FileSize + "kb以内或文件类型为" + Config.ImgExtensions, pass = false
                 }));
             }
         }
         else
         {
             return(Json(new ResultModel {
                 msg = "上传文件错误", pass = false
             }));
         }
     }
 }
        /// <summary>
        /// Generates image thumbnail and saves both to the file system
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="imageOrder"></param>
        /// <param name="imgType"></param>
        /// <returns></returns>
        private static Image SaveFile(HttpPostedFileBase postedFile, int imageOrder, ImageType imgType)
        {
            Image image = new Image()
            {
                Type     = imgType,
                Name     = Path.GetFileNameWithoutExtension(postedFile.FileName),
                FileName = Path.ChangeExtension(Guid.NewGuid().ToString(), Path.GetExtension(postedFile.FileName)),
                Order    = imageOrder
            };
            //TODO: might want to check whether there is a file with this Guid already
            string absoluteFilePath       = Path.Combine(ImageHelper.GetAbsoluteImageDirectory(imgType), image.FileName);
            string absoluteThumbnFilePath = Path.Combine(ImageHelper.GetAbsoluteImageDirectory(imgType), ImageHelper.GetThumbnailFileName(image.FileName));

            try
            {
                postedFile.SaveAs(absoluteFilePath);
                ImageProcessing.ImageProcessor.ResizeAndWriteFile(postedFile.InputStream, absoluteThumbnFilePath, Settings.ThumbnailWidth, Settings.ThumbnailQualityLevel);
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, nameof(BaseWithImagesBinder));

                if (File.Exists(absoluteFilePath))
                {
                    File.Delete(absoluteFilePath);
                }
                if (File.Exists(absoluteThumbnFilePath))
                {
                    File.Delete(absoluteThumbnFilePath);
                }
                return(null);
            }
            return(image);
        }
    /// <summary>
    /// Generates the QR code
    /// </summary>
    /// <param name="code">Code to generate by the QR code</param>
    /// <param name="size">Image size, image is rendered with recommended resolution for the QR code</param>
    /// <param name="encoding">Encoding, possible options (B - Byte, AN - Alphanumeric, N - Numeric)</param>
    /// <param name="version">QR code version (by default supported 1 to 10), additional data templates may be put into ~/App_Data/CMS_Modules/QRCode/Resources.zip</param>
    /// <param name="correction">Correction type, possible options (L, M, Q, H)</param>
    /// <param name="maxSideSize">Maximum size of the code in pixels, the code will be resized if larger than this size</param>
    /// <param name="fgColor">Foreground color</param>
    /// <param name="bgColor">Background color</param>
    private static CMSOutputResource GetQRCode(string code, string encoding, int size, int version, string correction, int maxSideSize, Color fgColor, Color bgColor)
    {
        QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();

        try
        {
            // Set encoding
            switch (encoding.ToLowerCSafe())
            {
                case "an":
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
                    break;

                case "n":
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC;
                    break;

                default:
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    break;
            }

            // Set scale
            try
            {
                qrCodeEncoder.QRCodeScale = size;
            }
            catch
            {
                qrCodeEncoder.QRCodeScale = 4;
            }

            // Set error correction
            switch (correction.ToLowerCSafe())
            {
                case "l":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
                    break;

                case "q":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
                    break;

                case "h":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
                    break;

                default:
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                    break;
            }

            // Set colors
            qrCodeEncoder.QRCodeForegroundColor = fgColor;
            qrCodeEncoder.QRCodeBackgroundColor = bgColor;

            Image image = null;

            // Attempt to process all versions
            while (version <= 40)
            {
                if (!QRVersionSupported(version))
                {
                    // Move to higher version
                    version++;

                    if (version > 40)
                    {
                        throw new Exception("Version higher than 40 is not supported.");
                    }
                    continue;
                }

                try
                {
                    // Try to get requested version
                    qrCodeEncoder.QRCodeVersion = version;

                    image = qrCodeEncoder.Encode(code);

                    break;
                }
                catch (IndexOutOfRangeException ex)
                {
                    // Try next version to fit the data
                    version++;

                    if (version > 40)
                    {
                        throw ex;
                    }
                }
            }

            byte[] bytes = ImageHelper.GetBytes(image, ImageFormat.Png);

            // Resize to a proper size
            if (maxSideSize > 0)
            {
                // Resize the image by image helper to a proper size
                ImageHelper ih = new ImageHelper(bytes);
                image = ih.GetResizedImage(maxSideSize);

                bytes = ImageHelper.GetBytes(image, ImageFormat.Png);
            }

            // Build the result
            var resource = new CMSOutputResource()
            {
                BinaryData = bytes,
                Name = code,
                Etag = "QRCode",
                LastModified = new DateTime(2012, 1, 1),
                ContentType = MimeTypeHelper.GetMimetype(".png"),
                FileName = "QRCode.png",
                Extension = ".png"
            };

            return resource;
        }
        catch (Exception ex)
        {
            // Report too long text
            string message = "[GetResource.GetQRCode]: Failed to generate QR code with text '" + code + "', this may be caused by the text being too long. Original message: " + ex.Message;

            var newEx = new Exception(message, ex);

            EventLogProvider.LogException("GetResource", "QRCODE", newEx);

            throw newEx;
        }
    }
Beispiel #33
0
    /// <summary>
    /// Provides operations necessary to create and store new attachment.
    /// </summary>
    private void HandleAttachmentUpload(bool fieldAttachment)
    {
        // New attachment
        AttachmentInfo newAttachment = null;

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

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


            #region "Check permissions"

            if (CheckPermissions)
            {
                CheckNodePermissions(node);
            }

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

            // Standard attachments
            if (DocumentID != 0)
            {
                // Check out the document
                if (AutoCheck)
                {
                    // Get original step Id
                    int originalStepId = node.DocumentWorkflowStepID;

                    // Get current step info
                    WorkflowStepInfo si = WorkflowManager.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);
                    }

                    using (CMSActionContext ctx = new CMSActionContext()
                    {
                        LogEvents = false
                    })
                    {
                        VersionManager.CheckOut(node, node.IsPublished, true);
                    }
                }

                // Handle field attachment
                if (fieldAttachment)
                {
                    // Extension of CMS file before saving
                    string oldExtension = node.DocumentType;

                    newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    // Update attachment field
                    DocumentHelper.UpdateDocument(node, TreeProvider);

                    // Different extension
                    if ((oldExtension != null) && !oldExtension.EqualsCSafe(node.DocumentType, true))
                    {
                        refreshTree = true;
                    }
                }
                // Handle grouped and unsorted attachments
                else
                {
                    // Grouped attachment
                    if (AttachmentGroupGUID != Guid.Empty)
                    {
                        newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }
                    // Unsorted attachment
                    else
                    {
                        newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }

                    // Log synchronization task if not under workflow
                    if (wi == null)
                    {
                        DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, TreeProvider);
                    }
                }

                // Check in the document
                if (AutoCheck)
                {
                    using (CMSActionContext ctx = new CMSActionContext()
                    {
                        LogEvents = false
                    })
                    {
                        VersionManager.CheckIn(node, null, null);
                    }
                }
            }

            // Temporary attachments
            if (FormGUID != Guid.Empty)
            {
                newAttachment = AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, SiteContext.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)
        {
            // Log the exception
            EventLogProvider.LogException("Content", "UploadAttachment", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;

            // Call aftersave javascript if exists
            if (!String.IsNullOrEmpty(AfterSaveJavascript))
            {
                if ((message == string.Empty) && (newAttachment != null))
                {
                    string url      = null;
                    string safeName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, SiteContext.CurrentSiteName);
                    if (node != null)
                    {
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                        if (si != null)
                        {
                            bool usePermanent = DocumentURLProvider.UsePermanentUrls(si.SiteName);
                            if (usePermanent)
                            {
                                url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, safeName));
                            }
                            else
                            {
                                url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(safeName, node.NodeAliasPath));
                            }
                        }
                    }
                    else
                    {
                        url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, safeName));
                    }
                    // Calling javascript function with parameters attachments url, name, width, height
                    if (!string.IsNullOrEmpty(AfterSaveJavascript))
                    {
                        Hashtable obj = new Hashtable();
                        if (ImageHelper.IsImage(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.IMG_URL]     = url;
                            obj[DialogParameters.IMG_TOOLTIP] = newAttachment.AttachmentName;
                            obj[DialogParameters.IMG_WIDTH]   = newAttachment.AttachmentImageWidth;
                            obj[DialogParameters.IMG_HEIGHT]  = newAttachment.AttachmentImageHeight;
                        }
                        else if (MediaHelper.IsFlash(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE]  = "flash";
                            obj[DialogParameters.FLASH_URL]    = url;
                            obj[DialogParameters.FLASH_EXT]    = newAttachment.AttachmentExtension;
                            obj[DialogParameters.FLASH_TITLE]  = newAttachment.AttachmentName;
                            obj[DialogParameters.FLASH_WIDTH]  = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.FLASH_HEIGHT] = DEFAULT_OBJECT_HEIGHT;
                        }
                        else if (MediaHelper.IsAudioVideo(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE] = "audiovideo";
                            obj[DialogParameters.AV_URL]      = url;
                            obj[DialogParameters.AV_EXT]      = newAttachment.AttachmentExtension;
                            obj[DialogParameters.AV_WIDTH]    = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.AV_HEIGHT]   = DEFAULT_OBJECT_HEIGHT;
                        }
                        else
                        {
                            obj[DialogParameters.LINK_URL]  = url;
                            obj[DialogParameters.LINK_TEXT] = newAttachment.AttachmentName;
                        }

                        // Calling javascript function with parameters attachments url, name, width, height
                        afterSaveScript += ScriptHelper.GetScript(string.Format(@"{5}
                        if (window.{0})
                        {{
                            window.{0}('{1}', '{2}', '{3}', '{4}', obj);
                        }}
                        else if((window.parent != null) && window.parent.{0})
                        {{
                            window.parent.{0}('{1}', '{2}', '{3}', '{4}', obj);
                        }}", AfterSaveJavascript, url, newAttachment.AttachmentName, newAttachment.AttachmentImageWidth, newAttachment.AttachmentImageHeight, CMSDialogHelper.GetDialogItem(obj)));
                    }
                }
                else
                {
                    afterSaveScript += ScriptHelper.GetAlertScript(message);
                }
            }

            // Create attachment info string
            string attachmentInfo = ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (IncludeNewItemInfo)) ? String.Format("'{0}', ", newAttachment.AttachmentGUID) : "";

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

            // Call function to refresh parent window
            afterSaveScript += ScriptHelper.GetScript(String.Format(@"
if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0} != null)){{ 
    window.parent.InitRefresh_{0}({1}, {2}, {3}, {4});
}}",
                                                                    ParentElemID,
                                                                    ScriptHelper.GetString(message.Trim()),
                                                                    (fullRefresh ? "true" : "false"),
                                                                    (refreshTree ? "true" : "false"),
                                                                    attachmentInfo + (InsertMode ? "'insert'" : "'update'")));

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript);
        }
    }
 private void Ok() {
   // TODO: Pass information to set the global settings...
   NewSettings.ShufflePictures = ShufflePictures;
   NewSettings.IncludeSubfolders = IncludeSubfolders;
   NewSettings.TransactionType = SelectedTransition;
   NewSettings.TransitionSpeed = SelectedTimeToShowImage;
   NewSettings.ImagePath = RecentFolderList[SelectedRecentFolder];
   ReorderRecentPathList();
   _globalParametersService.GlobalSettings = NewSettings;
   var list = new ImageHelper();
   var imageList = list.CheckForImagesForDirectory(NewSettings.ImagePath, NewSettings);
   if (imageList.Any()) {
     _globalParametersService.ImageList = imageList;
     CloseWindow();
   } else {
     ErrorVisibility = Visibility.Visible;
     ErrorMessage = "There are no images in that folder";
   }
 }
Beispiel #35
0
    /// <summary>
    /// Provides operations necessary to create and store new physical file.
    /// </summary>
    private void HandlePhysicalFilesUpload()
    {
        string message = string.Empty;

        try
        {
            // Check the allowed extensions
            CheckAllowedExtensions();

            // Prepare the file name
            string extension = Path.GetExtension(ucFileUpload.FileName);
            string fileName  = TargetFileName;
            if (String.IsNullOrEmpty(fileName))
            {
                fileName = Path.GetFileName(ucFileUpload.FileName);
            }
            else if (!fileName.Contains("."))
            {
                fileName += extension;
            }

            // Prepare the path
            if (String.IsNullOrEmpty(TargetFolderPath))
            {
                TargetFolderPath = "~/";
            }

            string filePath = TargetFolderPath;

            // Try to map virtual and relative path to server
            try
            {
                if (!Path.IsPathRooted(filePath))
                {
                    filePath = Server.MapPath(filePath);
                }
            }
            catch
            {
            }

            filePath = DirectoryHelper.CombinePath(filePath, fileName);

            // Ensure directory
            DirectoryHelper.EnsureDiskPath(filePath, SystemContext.WebApplicationPhysicalPath);

            // Ensure unique file name
            if (String.IsNullOrEmpty(TargetFileName) && File.Exists(filePath))
            {
                int    index    = 0;
                string basePath = filePath.Substring(0, filePath.Length - extension.Length);
                string newPath  = filePath;

                do
                {
                    index++;
                    newPath = basePath + "_" + index + extension;
                } while (File.Exists(newPath));

                filePath = newPath;
            }

            // Upload file
            if (ImageHelper.IsImage(extension) && ((ResizeToHeight > 0) || (ResizeToWidth > 0) || (ResizeToMaxSideSize > 0)))
            {
                byte[] data = ucFileUpload.FileBytes;

                // Resize the image
                ImageHelper img     = new ImageHelper(data);
                int[]       newSize = ImageHelper.EnsureImageDimensions(ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize, img.ImageWidth, img.ImageHeight);
                if ((newSize[0] != img.ImageWidth) || (newSize[1] != img.ImageHeight))
                {
                    data = img.GetResizedImageData(newSize[0], newSize[1]);
                }

                // Write to file
                File.WriteAllBytes(filePath, data);
            }
            else
            {
                File.WriteAllBytes(filePath, ucFileUpload.FileBytes);
            }
        }
        catch (Exception ex)
        {
            // Log the exception
            EventLogProvider.LogException("Uploader", "UploadPhysicalFile", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;
            if (!String.IsNullOrEmpty(message))
            {
                afterSaveScript = "setTimeout(\"alert(" + ScriptHelper.GetString(ScriptHelper.GetString(message), false) + ")\", 1);";
            }
            else
            {
                if (!string.IsNullOrEmpty(AfterSaveJavascript))
                {
                    afterSaveScript  = "if (window." + AfterSaveJavascript + " != null){window." + AfterSaveJavascript + "()}";
                    afterSaveScript += "else if ((window.parent != null) && (window.parent." + AfterSaveJavascript + " != null)){window.parent." + AfterSaveJavascript + "()}";
                }
                else
                {
                    afterSaveScript += "if ((window.parent != null) && (/parentelemid=" + ParentElemID + "/i.test(window.location.href)) && (window.parent.InitRefresh_" + ParentElemID + " != null)){window.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", false, false);}";
                }
            }

            afterSaveScript = ScriptHelper.GetScript(afterSaveScript);

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript);
        }
    }
    private void HandleMetaFileUpload()
    {
        string message = string.Empty;
        MetaFileInfo mfi = null;

        try
        {
            // Check the allowed extensions
            CheckAllowedExtensions();

            if (InsertMode)
            {
                // Create new meta file
                mfi = new MetaFileInfo(FileUploadControl.PostedFile, ObjectID, ObjectType, Category);
                mfi.MetaFileSiteID = SiteID;
            }
            else
            {
                if (MetaFileID > 0)
                {
                    mfi = MetaFileInfoProvider.GetMetaFileInfo(MetaFileID);
                }
                else
                {
                    DataSet ds = MetaFileInfoProvider.GetMetaFilesWithoutBinary(ObjectID, ObjectType, Category, null, null);
                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        mfi = new MetaFileInfo(ds.Tables[0].Rows[0]);
                    }
                }

                if (mfi != null)
                {
                    string fileExt = Path.GetExtension(FileUploadControl.FileName);
                    // Init the MetaFile data
                    mfi.MetaFileName = URLHelper.GetSafeFileName(FileUploadControl.FileName, null);
                    mfi.MetaFileExtension = fileExt;

                    mfi.MetaFileSize = Convert.ToInt32(FileUploadControl.PostedFile.InputStream.Length);
                    mfi.MetaFileMimeType = MimeTypeHelper.GetMimetype(fileExt);
                    mfi.InputStream = StreamWrapper.New(FileUploadControl.PostedFile.InputStream);

                    // Set image properties
                    if (ImageHelper.IsImage(mfi.MetaFileExtension))
                    {
                        // Make MetaFile binary load from InputStream
                        mfi.MetaFileBinary = null;
                        ImageHelper ih = new ImageHelper(mfi.MetaFileBinary);
                        mfi.MetaFileImageHeight = ih.ImageHeight;
                        mfi.MetaFileImageWidth = ih.ImageWidth;
                    }
                }
            }

            if (mfi != null)
            {
                // Save file to the database
                MetaFileInfoProvider.SetMetaFileInfo(mfi);
            }
        }
        catch (Exception ex)
        {
            // Log the exception
            EventLogProvider.LogException("Uploader", "UploadMetaFile", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;
            if (String.IsNullOrEmpty(message))
            {
                if (!string.IsNullOrEmpty(AfterSaveJavascript))
                {
                    afterSaveScript = String.Format(
        @"
        if (window.{0} != null) {{
        window.{0}(files)
        }} else if ((window.parent != null) && (window.parent.{0} != null)) {{
        window.parent.{0}(files)
        }}
        ",
                        AfterSaveJavascript
                    );
                }
                else
                {
                    afterSaveScript = String.Format(@"
                        if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0}))
                        {{
                            window.parent.InitRefresh_{0}('{1}', false, false, {2});
                        }}
                        else {{
                            if ('{1}' != '') {{
                                alert('{1}');
                            }}
                        }}", ParentElemID, ScriptHelper.GetString(message.Trim(), false), mfi.MetaFileID.ToString() + (InsertMode ? ",'insert'" : ",'update'"));
                }
            }
            else
            {
                afterSaveScript += ScriptHelper.GetAlertScript(message, false);
            }

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript, true);
        }
    }
Beispiel #37
0
    private void HandleMetaFileUpload()
    {
        string       message = string.Empty;
        MetaFileInfo mfi     = null;

        try
        {
            // Check the allowed extensions
            CheckAllowedExtensions();

            if (InsertMode)
            {
                // Create new meta file
                mfi = new MetaFileInfo(FileUploadControl.PostedFile, ObjectID, ObjectType, Category);
                mfi.MetaFileSiteID = SiteID;
            }
            else
            {
                if (MetaFileID > 0)
                {
                    mfi = MetaFileInfoProvider.GetMetaFileInfo(MetaFileID);
                }
                else
                {
                    DataSet ds = MetaFileInfoProvider.GetMetaFilesWithoutBinary(ObjectID, ObjectType, Category, null, null);
                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        mfi = new MetaFileInfo(ds.Tables[0].Rows[0]);
                    }
                }

                if (mfi != null)
                {
                    string fileExt = Path.GetExtension(FileUploadControl.FileName);
                    // Init the MetaFile data
                    mfi.MetaFileName      = URLHelper.GetSafeFileName(FileUploadControl.FileName, null);
                    mfi.MetaFileExtension = fileExt;

                    mfi.MetaFileSize     = Convert.ToInt32(FileUploadControl.PostedFile.InputStream.Length);
                    mfi.MetaFileMimeType = MimeTypeHelper.GetMimetype(fileExt);
                    mfi.InputStream      = StreamWrapper.New(FileUploadControl.PostedFile.InputStream);

                    // Set image properties
                    if (ImageHelper.IsImage(mfi.MetaFileExtension))
                    {
                        // Make MetaFile binary load from InputStream
                        mfi.MetaFileBinary = null;
                        ImageHelper ih = new ImageHelper(mfi.MetaFileBinary);
                        mfi.MetaFileImageHeight = ih.ImageHeight;
                        mfi.MetaFileImageWidth  = ih.ImageWidth;
                    }
                }
            }

            if (mfi != null)
            {
                // Save file to the database
                MetaFileInfoProvider.SetMetaFileInfo(mfi);
            }
        }
        catch (Exception ex)
        {
            // Log the exception
            EventLogProvider.LogException("Uploader", "UploadMetaFile", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;
            if (String.IsNullOrEmpty(message))
            {
                if (!string.IsNullOrEmpty(AfterSaveJavascript))
                {
                    afterSaveScript = String.Format(@"
                        if (window.{0} != null) {{
                            window.{0}()
                        }} else if ((window.parent != null) && (window.parent.{0} != null)) {{
                            window.parent.{0}() 
                        }}", AfterSaveJavascript);
                }
                else
                {
                    afterSaveScript = String.Format(@"
                        if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0}))
                        {{
                            window.parent.InitRefresh_{0}('{1}', false, false, {2});
                        }}
                        else {{ 
                            if ('{1}' != '') {{
                                alert('{1}');
                            }}
                        }}", ParentElemID, ScriptHelper.GetString(message.Trim(), false), mfi.MetaFileID.ToString() + (InsertMode ? ",'insert'" : ",'update'"));
                }
            }
            else
            {
                afterSaveScript += ScriptHelper.GetAlertScript(message, false);
            }

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript, true);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        RegisterTrimScript();

        if (LoadImageType != null)
        {
            LoadImageType();
        }

        ltlScript.Text = "";

        if (!URLHelper.IsPostback())
        {
            // Display image if available data
            if (imageType != ImageHelper.ImageTypeEnum.None)
            {
                if (InitializeProperties != null)
                {
                    InitializeProperties();
                }

                if (!LoadingFailed)
                {
                    currentFormat = imgHelper.ImageFormatToString();
                }
            }

            // Create first version on first load (original)
            if (ImgHelper != null)
            {
                CreateVersion(ImgHelper.SourceData);
            }
        }
        else
        {
            // Load current version to edit
            tempFile = TempFileInfoProvider.GetTempFileInfo(InstanceGUID, CurrentVersion);
            if (tempFile != null)
            {
                tempFile.Generalized.EnsureBinaryData();
                ImgHelper = new ImageHelper(tempFile.FileBinary);
                currentFormat = imgHelper.ImageFormatToString();
            }

            if (!IsUndoRedoPossible() && (InitializeProperties != null))
            {
                InitializeProperties();
            }

            if (!LoadingFailed && (imgHelper != null))
            {
                currentFormat = imgHelper.ImageFormatToString();
            }
        }

        InitializeStrings(!RequestHelper.IsPostBack());
        InitializeFields();

        if (!URLHelper.IsPostback())
        {
            // Initialize labels depending on image type in parent control
            if (InitializeLabels != null)
            {
                InitializeLabels(true);
            }
        }

        // Show tab 'Properties'
        if (ValidationHelper.GetBoolean(hdnShowProperties.Value, false))
        {
            ScriptHelper.RegisterStartupScript(this, typeof(string), "ShowProperties", ScriptHelper.GetScript("ShowProperties(true, '" + hdnShowProperties.ClientID + "');"));
        }

        if (!IsPreview)
        {
            // Enable or disable meta data editor
            metaDataEditor.Enabled = Enabled;
        }
    }
        /// <summary>
        /// Saves the local Avatar
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void UploadUpdate_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            if (this.File.PostedFile == null || this.File.PostedFile.FileName.Trim().Length <= 0 ||
                this.File.PostedFile.ContentLength <= 0)
            {
                return;
            }

            long x          = this.Get <BoardSettings>().AvatarWidth;
            long y          = this.Get <BoardSettings>().AvatarHeight;
            var  avatarSize = this.Get <BoardSettings>().AvatarSize;

            Stream resized = null;

            try
            {
                using (var img = Image.FromStream(this.File.PostedFile.InputStream))
                {
                    if (img.Width > x || img.Height > y)
                    {
                        this.PageContext.AddLoadMessage(
                            $"{this.GetTextFormatted("WARN_TOOBIG", x, y)} {this.GetTextFormatted("WARN_SIZE", img.Width, img.Height)} {this.GetText("EDIT_AVATAR", "WARN_RESIZED")}",
                            MessageTypes.warning);

                        resized = ImageHelper.GetResizedImageStreamFromImage(img, x, y);
                    }
                }

                // Delete old first...
                this.GetRepository <User>().DeleteAvatar(this.currentUserId);

                if (this.Get <BoardSettings>().UseFileTable)
                {
                    var image = Image.FromStream(resized ?? this.File.PostedFile.InputStream);

                    var memoryStream = new MemoryStream();
                    image.Save(memoryStream, image.RawFormat);
                    memoryStream.Position = 0;

                    this.GetRepository <User>().SaveAvatar(
                        this.currentUserId,
                        null,
                        memoryStream,
                        this.File.PostedFile.ContentType);
                }
                else
                {
                    var uploadFolderPath = this.Get <HttpRequestBase>().MapPath(
                        string.Concat(BaseUrlBuilder.ServerFileRoot, BoardFolders.Current.Uploads));

                    // check if Uploads folder exists
                    if (!Directory.Exists(uploadFolderPath))
                    {
                        Directory.CreateDirectory(uploadFolderPath);
                    }

                    var fileName = this.File.PostedFile.FileName;

                    var pos = fileName.LastIndexOfAny(new[] { '/', '\\' });

                    if (pos >= 0)
                    {
                        fileName = fileName.Substring(pos + 1);
                    }

                    // filename can be only 255 characters long (due to table column)
                    if (fileName.Length > 255)
                    {
                        fileName = fileName.Substring(fileName.Length - 255);
                    }

                    var newFileName = $"{this.currentUserId}{Path.GetExtension(fileName)}";

                    var filePath = Path.Combine(uploadFolderPath, newFileName);

                    // Delete old avatar
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }

                    var avatarImage = Image.FromStream(resized ?? this.File.PostedFile.InputStream);

                    using (var memory = new MemoryStream())
                    {
                        using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                        {
                            avatarImage.Save(memory, avatarImage.RawFormat);
                            var bytes = memory.ToArray();
                            fs.Write(bytes, 0, bytes.Length);
                        }
                    }

                    this.GetRepository <User>().SaveAvatar(
                        this.currentUserId,
                        $"{BoardInfo.ForumBaseUrl}{BoardFolders.Current.Uploads}/{newFileName}",
                        null,
                        null);
                }

                // clear the cache for this user...
                this.Get <IRaiseEvent>().Raise(new UpdateUserEvent(this.currentUserId));

                if (avatarSize > 0 && this.File.PostedFile.ContentLength >= avatarSize && resized == null)
                {
                    this.PageContext.AddLoadMessage(
                        $"{this.GetTextFormatted("WARN_BIGFILE", avatarSize)} {this.GetTextFormatted("WARN_FILESIZE", this.File.PostedFile.ContentLength)}",
                        MessageTypes.warning);
                }

                this.BindData();
            }
            catch (Exception exception)
            {
                this.Logger.Log(
                    exception.Message,
                    EventLogTypes.Error,
                    this.PageContext.CurrentUserData.UserName,
                    string.Empty,
                    exception);

                // image is probably invalid...
                this.PageContext.AddLoadMessage(this.GetText("EDIT_AVATAR", "INVALID_FILE"), MessageTypes.danger);
            }
        }
Beispiel #40
0
        /// <summary>
        /// 根据ID处理临时图片
        /// </summary>
        /// <param name="GraphicID"></param>
        public void SetGraphicColor(string GraphicID, string tmpname)
        {
            if (GraphicID == "")
            {
                return;
            }
            string fileName = tmpname;
            string newName = GetGraphicPath(GraphicID);

            Image img = Image.FromFile(fileName);

            Bitmap btm = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            using (Graphics g1 = Graphics.FromImage(btm))
            {
                g1.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g1.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g1.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g1.DrawImage(img, 0, 0);
            }

            #region 颜色替换
            //for (int x = 0; x < btm.Width; x++)
            //{
            //    for (int y = 0; y < btm.Height; y++)
            //    {
            //        Color cTmp = btm.GetPixel(x, y);
            //        Color c = ColorTranslator.FromHtml("#ffffff");
            //        if (cTmp.ToArgb() == c.ToArgb())
            //        {
            //            btm.SetPixel(x, y, ColorTranslator.FromHtml("#C0C0C0"));
            //        }
            //    }
            //}
            #endregion

            #region 加水印
            Graphics g = Graphics.FromImage(btm);
            ImageHelper m_img = new ImageHelper();
            m_img.addWatermarkImage(g, AppDomain.CurrentDomain.BaseDirectory + AppConfig.WaterMarkPath, 0, 0, 119, 68);
            #endregion
            btm.Save(newName, ImageFormat.Gif);
            btm.Dispose();
            img.Dispose();
            File.Delete(fileName);
        }
        /// <summary>
        /// Provides operations necessary to create and store new metafile.
        /// </summary>
        /// <param name="args">Upload arguments.</param>
        /// <param name="context">HttpContext instance.</param>
        private void HandleMetafileUpload(UploaderHelper args, HttpContext context)
        {
            MetaFileInfo mfi = null;

            try
            {
                // Check the allowed extensions
                args.IsExtensionAllowed();

                if (args.IsInsertMode)
                {
                    // Create new metafile info
                    mfi = new MetaFileInfo(args.FilePath, args.MetaFileArgs.ObjectID, args.MetaFileArgs.ObjectType, args.MetaFileArgs.Category);
                    mfi.MetaFileSiteID = args.MetaFileArgs.SiteID;
                }
                else
                {
                    if (args.MetaFileArgs.MetaFileID > 0)
                    {
                        mfi = MetaFileInfoProvider.GetMetaFileInfo(args.MetaFileArgs.MetaFileID);
                    }
                    else
                    {
                        DataSet ds = MetaFileInfoProvider.GetMetaFilesWithoutBinary(args.MetaFileArgs.ObjectID, args.MetaFileArgs.ObjectType, args.MetaFileArgs.Category, null, null);
                        if (!DataHelper.DataSourceIsEmpty(ds))
                        {
                            mfi = new MetaFileInfo(ds.Tables[0].Rows[0]);
                        }
                    }

                    if (mfi != null)
                    {
                        FileInfo fileInfo = FileInfo.New(args.FilePath);
                        // Init the MetaFile data
                        mfi.MetaFileName = URLHelper.GetSafeFileName(fileInfo.Name, null);
                        mfi.MetaFileExtension = fileInfo.Extension;

                        FileStream file = fileInfo.OpenRead();
                        mfi.MetaFileSize = Convert.ToInt32(fileInfo.Length);
                        mfi.MetaFileMimeType = MimeTypeHelper.GetMimetype(mfi.MetaFileExtension);
                        mfi.InputStream = file;

                        // Set image properties
                        if (ImageHelper.IsImage(mfi.MetaFileExtension))
                        {
                            ImageHelper ih = new ImageHelper(mfi.MetaFileBinary);
                            mfi.MetaFileImageHeight = ih.ImageHeight;
                            mfi.MetaFileImageWidth = ih.ImageWidth;
                        }
                    }
                }

                if (mfi != null)
                {
                    MetaFileInfoProvider.SetMetaFileInfo(mfi);
                }
            }
            catch (Exception ex)
            {
                args.Message = ex.Message;
            }
            finally
            {
                if (String.IsNullOrEmpty(args.Message))
                {
                    if (!string.IsNullOrEmpty(args.AfterSaveJavascript))
                    {
                        args.AfterScript = String.Format(@"
                        if (window.{0} != null) {{
                            window.{0}()
                        }} else if ((window.parent != null) && (window.parent.{0} != null)) {{
                            window.parent.{0}()
                        }}", args.AfterSaveJavascript);
                    }
                    else
                    {
                        args.AfterScript = String.Format(@"
                        if (window.InitRefresh_{0})
                        {{
                            window.InitRefresh_{0}('{1}', false, false, {2});
                        }}
                        else {{
                            if ('{1}' != '') {{
                                alert('{1}');
                            }}
                        }}", args.ParentElementID, ScriptHelper.GetString(args.Message.Trim(), false), mfi.MetaFileID);
                    }
                }
                else
                {
                    args.AfterScript += ScriptHelper.GetAlertScript(args.Message, false);
                }

                args.AddEventTargetPostbackReference();
                context.Response.Write(args.AfterScript);
                context.Response.Flush();
            }
        }
Beispiel #42
0
 public Image Apply(Image sourceImage, Matrix matrix)
 {
     return(ImageHelper.Adjust(sourceImage, Brightness, Contrast, Gamma));
 }
Beispiel #43
0
 /// <summary>
 /// 根据Url获取图片
 /// </summary>
 /// <param name="item">参数类对象</param>
 /// <returns>返回图片</returns>
 internal Image GetImage(HttpItem item)
 {
     item.ResultType = ResultType.Byte;
     return(ImageHelper.ByteToImage(GetHtml(item).ResultByte));
 }
    /// <summary>
    /// Gets image dimensions from external URL.
    /// </summary>
    private void GetExternalImageDimensions(string imageUrl)
    {
        try
        {
            WebClient wc = new WebClient();
            byte[] img = wc.DownloadData(imageUrl);
            wc.Dispose();

            var ih = new ImageHelper(img);

            if (ih.ImageWidth > 0)
            {
                mWidth = ih.ImageWidth;
            }
            if (ih.ImageHeight > 0)
            {
                mHeight = ih.ImageHeight;
            }
        }
        catch
        {
        }
    }
Beispiel #45
0
        /// <summary>
        /// 上传图片处理
        /// </summary>
        /// <param name="file"></param>
        /// <param name="imageUploadConfig">图片上传配置基类或其派生类</param>
        /// <returns></returns>
        public CommonResult ImageHandler(HttpPostedFileBase postFile, ImageUploadBaseConfig imageUploadConfig, string strUserName, DataModel dataModel, ActionType actionType)
        {
            try
            {
                #region 验证并保存原图
                //验证目标目录是否存在
                if (!Directory.Exists(PathHelper.GetMapPath(imageUploadConfig.SavePath)))
                {
                    return(CommonResult.Instance("找不到指定的上传文件目录"));
                }
                //获取文件扩展名
                string fileExtension = Path.GetExtension(postFile.FileName);
                //检查文件是否为可上传的文件格式
                bool isAllowExtension = imageUploadConfig.AllowExtension.ToStr().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Contains(fileExtension);
                if (!isAllowExtension)
                {
                    return(CommonResult.Instance("不允许上传的图片类型"));
                }
                //上传文件大小限制
                if (postFile.ContentLength > imageUploadConfig.MaxSize * 1024)
                {
                    return(CommonResult.Instance(string.Format("上传的图片不能大于{0}K", imageUploadConfig.MaxSize)));
                }
                //设置图片名称
                var fileName = dataModel["DefinedName"].ToStr();                //postFile.FileName;
                //取得扩展名
                string strExt = dataModel["Ext"].ToStr();
                //取得图片名称(去扩展名)
                string strFileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
                //设置图片存放目录(虚拟路径)
                string strFileSaveVirtualPath = string.Format("{0}/{1}{2}", imageUploadConfig.SavePath, fileName, strExt);
                //设置图片存放目录(物理路径)
                string strFileSavePath = PathHelper.GetMapPath(strFileSaveVirtualPath);

                //是否处理相同路径图片
                this.OldImageHandler(strFileSaveVirtualPath, imageUploadConfig, strUserName);
                //if(FileHelper.Exists(strFileSavePath))
                //{
                //	#region 处理同路径旧图片
                //	//File.Delete(strFileSavePath);
                //	string strNewFileName = FileHelper.ResetFileMinName(strFileSavePath);
                //	if(!FileHelper.RenameFile(strFileSavePath,strNewFileName))//重命名旧文件
                //	{
                //		return CommonResult.Instance("旧文件重命名失败");
                //	}
                //	//更新旧文件的信息
                //	Document oldDocumentModel = new Document();
                //	oldDocumentModel.UID = AllServices.DocumentService.GetUID(strFileSaveVirtualPath);
                //	oldDocumentModel.DocumentName = strNewFileName;
                //	oldDocumentModel.DocumentPath = string.Format("{0}/{1}",imageUploadConfig.SavePath,strNewFileName);
                //	oldDocumentModel.Editor = stringUserName;
                //	oldDocumentModel.EditTime = DateTime.Now;
                //	oldDocumentModel.State = Convert.ToInt32(ItemState.Disable);
                //	AllServices.DocumentService.Update(oldDocumentModel);
                //	#endregion

                //}
                //保存图片
                postFile.SaveAs(strFileSavePath);
                #endregion

                #region 处理图片
                string mode    = imageUploadConfig.Mode;
                string strJson = string.Empty;

                if (!mode.Contains("None"))
                {
                    //处理后的图片保存目录
                    string imgHandlerDir = imageUploadConfig.SavePath + "/" + "m";
                    if (!Directory.Exists(PathHelper.GetMapPath(imgHandlerDir)))
                    {
                        Directory.CreateDirectory(PathHelper.GetMapPath(imgHandlerDir));
                    }
                    //目标图片名称
                    string fileNameByTarget = Path.GetFileName(strFileSavePath);
                    //目标图片的虚拟路径
                    string fileSaveVirtualPathByTarget = string.Format("{0}/{1}", imgHandlerDir, fileNameByTarget);
                    //目标图片的物理路径
                    string fileSavePathByTarget = PathHelper.GetMapPath(fileSaveVirtualPathByTarget);
                    //处理图片
                    ImageHelper.CompressType cType = ImageHelper.CompressType.Zoom;
                    switch (mode.ToLower())
                    {
                    case "cut":
                        cType = ImageHelper.CompressType.WidthAndHeightCut;
                        break;

                    case "zoom":
                        cType = ImageHelper.CompressType.Zoom;
                        break;

                    case "stretch":
                        cType = ImageHelper.CompressType.WidthAndHeight;
                        break;
                    }
                    ImageHelper.Thumb(strFileSavePath, fileSavePathByTarget, imageUploadConfig.Width, imageUploadConfig.Height, cType, imageUploadConfig.Quality);
                    //添加上传文件记录(处理后的图片)
                    AllServices.DocumentService.Add(new Models.Document()
                    {
                        //DocumentName = fileNameByTarget,
                        ////File_Extension = fileExtension.ToLower(),
                        //DocumentPath = fileSaveVirtualPathByTarget,
                        //PictureSize = new System.IO.FileInfo(fileSavePathByTarget).Length.ToStr(),
                        ////IsSystemCreate = true
                    });
                    //删除原图
                    if (imageUploadConfig.DelOriginalPhoto)
                    {
                        File.Delete(strFileSavePath);
                    }
                    else
                    {
                        //添加上传文件记录(原图)
                        AllServices.DocumentService.Add(new Models.Document()
                        {
                            //DocumentName = fileName,
                            //File_Extension = fileExtension.ToLower(),
                            //DocumentPath = strFileSaveVirtualPath,
                            //PictureSize = postFile.ContentLength.ToStr(),
                            //IsSystemCreate = false
                        });
                    }
                    strFileSaveVirtualPath = fileSaveVirtualPathByTarget;
                }
                #endregion

                //释放图片资源
                postFile.InputStream.Close();
                postFile.InputStream.Dispose();

                CommonResult commonResult = this.AddImageHandler(0, fileName, strFileSaveVirtualPath, dataModel["Ext"].ToStr(), dataModel["Size"].ToStr(), dataModel["DpiID"].ToInt32(), actionType, strUserName);
                return(commonResult);
            }
            catch (Exception ex)
            {
                return(CommonResult.Instance(ex.ToString()));
            }
        }
        /// <summary>
        ///     Execute a command asynchronously.
        /// </summary>
        /// <param name="command">Command to execute.</param>
        /// <returns>
        ///     Task which will be completed once the command has been executed.
        /// </returns>
        public async Task HandleAsync(IMessageContext context, SendTemplateEmail command)
        {
            var loader         = new TemplateLoader();
            var templateParser = new TemplateParser();

            var layout = loader.Load("Layout");

            var template = loader.Load(command.TemplateName);
            var html     = templateParser.RunAll(template, command.Model);

            if (html.IndexOf("src=\"cid:", StringComparison.OrdinalIgnoreCase) == -1)
            {
                html = html.Replace(@"src=""", @"src=""cid:");
            }

            string complete;

            try
            {
                complete = templateParser.RunFormatterOnly(layout,
                                                           new { Title = command.MailTitle, Body = html });
            }
            catch (Exception)
            {
                throw;
            }

            var msg = new EmailMessage(command.To)
            {
                Subject = command.Subject, HtmlBody = complete
            };

            foreach (var resource in template.Resources)
            {
                var linkedResource = new EmailResource(resource.Key, resource.Value);

                var reader     = new BinaryReader(resource.Value);
                var dimensions = ImageHelper.GetDimensions(reader);
                var key        = string.Format("src=\"cid:{0}\"", resource.Key);
                complete = complete.Replace(key,
                                            string.Format("{0} width=\"{1}\" height=\"{2}\" style=\"border: 1px solid #000\"", key,
                                                          dimensions.Width, dimensions.Height));
                resource.Value.Position = 0;

                msg.Resources.Add(linkedResource);
            }
            foreach (var resource in layout.Resources)
            {
                var linkedResource = new EmailResource(resource.Key, resource.Value);

                var reader     = new BinaryReader(resource.Value);
                var dimensions = ImageHelper.GetDimensions(reader);
                var key        = string.Format("src=\"cid:{0}\"", resource.Key);
                complete = complete.Replace(key,
                                            string.Format("{0} width=\"{1}\" height=\"{2}\"", key, dimensions.Width, dimensions.Height));
                resource.Value.Position = 0;

                msg.Resources.Add(linkedResource);
            }
            if (command.Resources != null)
            {
                foreach (var resource in command.Resources)
                {
                    msg.Resources.Add(resource);
                }
            }
            msg.HtmlBody = complete;

            var sendEmail = new SendEmail(msg);
            await context.SendAsync(sendEmail);
        }
        /// <inheritdoc />
        public async Task <(string path, string?mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options)
        {
            ItemImageInfo originalImage = options.Image;
            BaseItem      item          = options.Item;

            string          originalImagePath = originalImage.Path;
            DateTime        dateModified      = originalImage.DateModified;
            ImageDimensions?originalImageSize = null;

            if (originalImage.Width > 0 && originalImage.Height > 0)
            {
                originalImageSize = new ImageDimensions(originalImage.Width, originalImage.Height);
            }

            if (!_imageEncoder.SupportsImageEncoding)
            {
                return(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
            }

            var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false);

            originalImagePath = supportedImageInfo.path;

            if (!File.Exists(originalImagePath))
            {
                return(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
            }

            dateModified = supportedImageInfo.dateModified;
            bool requiresTransparency = _transparentImageTypes.Contains(Path.GetExtension(originalImagePath));

            bool             autoOrient  = false;
            ImageOrientation?orientation = null;

            if (item is Photo photo)
            {
                if (photo.Orientation.HasValue)
                {
                    if (photo.Orientation.Value != ImageOrientation.TopLeft)
                    {
                        autoOrient  = true;
                        orientation = photo.Orientation;
                    }
                }
                else
                {
                    // Orientation unknown, so do it
                    autoOrient  = true;
                    orientation = photo.Orientation;
                }
            }

            if (options.HasDefaultOptions(originalImagePath, originalImageSize) && (!autoOrient || !options.RequiresAutoOrientation))
            {
                // Just spit out the original file if all the options are default
                return(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
            }

            ImageDimensions newSize = ImageHelper.GetNewImageSize(options, null);
            int             quality = options.Quality;

            ImageFormat outputFormat  = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency);
            string      cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer);

            try
            {
                if (!File.Exists(cacheFilePath))
                {
                    if (options.CropWhiteSpace && !SupportsTransparency(originalImagePath))
                    {
                        options.CropWhiteSpace = false;
                    }

                    string resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat);

                    if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase))
                    {
                        return(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
                    }
                }

                return(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath));
            }
            catch (Exception ex)
            {
                // If it fails for whatever reason, return the original image
                _logger.LogError(ex, "Error encoding image");
                return(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
            }
        }
    /// <summary>
    /// Loads preview according item type.
    /// </summary>
    /// <param name="fileName">Name fo the file to load preview for</param>
    private void LoadPreview(string fileName)
    {
        // Load preview
        string url = "";
        if (this.GetItemUrl != null)
        {
            url = this.GetItemUrl(fileName);
        }

        string ext = Path.GetExtension(fileName);
        if (ImageHelper.IsImage(ext))
        {
            this.hdnPreviewType.Value = "image";

            // Get image physical path
            string filePath = (string.IsNullOrEmpty(this.FolderPath)) ? fileName : DirectoryHelper.CombinePath(this.FolderPath, fileName);
            filePath = MediaFileInfoProvider.GetMediaFilePath(CMSContext.CurrentSiteName, this.LibraryInfo.LibraryFolder, filePath);

            if (File.Exists(filePath))
            {
                // Load image info
                ImageHelper ih = new ImageHelper();
                ih.LoadImage(File.ReadAllBytes(filePath));

                // Get new dimensions
                int origWidth = ValidationHelper.GetInteger(ih.ImageWidth, 0);
                int origHeight = ValidationHelper.GetInteger(ih.ImageHeight, 0);
                int[] newDimensions = ImageHelper.EnsureImageDimensions(0, 0, 300, origWidth, origHeight);

                // Image preview
                this.imagePreview.ShowFileIcons = false;
                this.imagePreview.URL = url;
                this.imagePreview.SizeToURL = false;
                this.imagePreview.Width = newDimensions[0];
                this.imagePreview.Height = newDimensions[1];
                this.imagePreview.Alt = fileName;
                this.imagePreview.Tooltip = fileName;

                // Open link
                this.lnkOpenImage.Target = "_blank";
                this.lnkOpenImage.Text = GetString("media.file.openimg");
                this.lnkOpenImage.ToolTip = GetString("media.file.openimg");
                this.lnkOpenImage.NavigateUrl = url;
            }
        }
        else if (CMS.GlobalHelper.MediaHelper.IsAudioVideo(ext) || CMS.GlobalHelper.MediaHelper.IsFlash(ext))
        {
            this.hdnPreviewType.Value = "media";

            // Media preview
            this.mediaPreview.Height = 200;
            this.mediaPreview.Width = 300;
            this.mediaPreview.AVControls = true;
            this.mediaPreview.Loop = true;
            this.mediaPreview.Url = url;
            this.mediaPreview.Type = ext;

            // Open link
            this.lnkOpenMedia.Target = "_blank";
            this.lnkOpenMedia.Text = GetString("media.file.openimg");
            this.lnkOpenMedia.ToolTip = GetString("media.file.openimg");
            this.lnkOpenMedia.NavigateUrl = url;
        }
        else
        {
            this.hdnPreviewType.Value = "other";

            // Open link
            this.lnkOpenOther.Target = "_blank";
            this.lnkOpenOther.Text = GetString("general.open");
            this.lnkOpenOther.ToolTip = GetString("general.open");
            this.lnkOpenOther.NavigateUrl = url;
        }
    }
Beispiel #49
0
 public Close()
 {
     InitializeComponent();
     ButtonClearFilters.Image.Source = ImageHelper.GenerateImage("IconClearAllFilters.png");
     ButtonClose.Image.Source        = ImageHelper.GenerateImage("IconClose.png");
 }