public static string GetImgPath(string categFolderName, string folderImgName, string imgJsonString, string imgSize = CONSTANT.MIDDLE_FILE_NAME_PREFIX)
        {
            ImgJson imgJsonObject = ImgJson.Parse(imgJsonString) ?? new ImgJson {
                CountHistory = 0, ImgJsonOrderList = null
            };

            return(GetImgPath(categFolderName, folderImgName, imgJsonObject, imgSize));
        }
        /// <summary>
        /// Получает название файлов из json строки JsonList преобразуя в список объектов типа AdImgModelView
        /// </summary>
        /// <param name="jsonList">json строка</param>
        /// <returns></returns>
        public static List <AdImgModelView> GetImages(string jsonList)
        {
            if (jsonList == null)
            {
                throw new ArgumentNullException($"Hey! {nameof(jsonList)} must be not null");
            }

            ImgJson jsonResult = ImgJson.Parse(jsonList);

            return(GetImages(jsonResult.ImgJsonOrderList));
        }
Exemple #3
0
        public static ImgDescView ToView(ImgJson imgJson)
        {
            if (imgJson == null)
            {
                return(null);
            }

            var item = new ImgDescView
            {
                desc = imgJson.Desc,
                img  = imgJson.Img
            };

            return(item);
        }
Exemple #4
0
        /// <summary>
        /// 获取图片分类信息
        /// </summary>
        /// <returns>返回json类型的图片数组</returns>
        public ImgJson getImageType()
        {
            string curl = @"http://wallpaper.apc.360.cn/index.php?c=WallPaper&a=getAllCategoriesV2";

            //创建一个HttpWebRequest对象
            req = (HttpWebRequest)HttpWebRequest.Create(curl);
            //设置它提交数据的方式GET
            req.Method = "GET";
            StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream());
            //获取返回的XML数据
            string Reader            = Unicode2String(sr.ReadToEnd());
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ImgJson it = jss.Deserialize <ImgJson>(Reader);

            return(it);
        }
Exemple #5
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

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

            if (string.Compare(action, "adminLogin", false) == 0)
            {
                int varifyCode = 0;
                if (int.TryParse(context.Request["captcha"], out varifyCode))
                {
                    string json = string.Empty;
                    Debug.Write(varifyCode);
                    int sCode = -1;
                    var o     = context.Session["varifyCode"];
                    if (o == null)
                    {
                        json = JsonConvert.SerializeObject(new { IsOk = "NoOk", Msg = "请刷新验证码再试" });
                        context.Response.Write(json);
                        return;
                    }
                    sCode = int.Parse(o.ToString());

                    if (sCode == varifyCode)
                    {
                        //验证用户名密码

                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "admin", DateTime.Now, DateTime.Now.AddDays(1), false, "password", "/");
                        string     authticket            = FormsAuthentication.Encrypt(ticket);
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, authticket);
                        cookie.Secure  = false;
                        cookie.Expires = ticket.Expiration;
                        cookie.Path    = FormsAuthentication.FormsCookiePath;
                        context.Response.Cookies.Add(cookie);

                        json = JsonConvert.SerializeObject(new { IsOk = "Ok" });
                        context.Response.Write(json);
                    }
                    else
                    {
                        json = JsonConvert.SerializeObject(new { IsOk = "NoOk", Msg = "验证码输入有误,请刷新验证码" });
                        context.Response.Write(json);
                        return;
                    }
                }
                else
                {
                    string json = JsonConvert.SerializeObject(new { IsOk = "NoOk", Msg = "" });
                    context.Response.Write(json);
                    return;
                }
            }
            else if (string.Compare(action, "yzm", false) == 0)
            {
                ValidateCode c    = new ValidateCode();
                string       code = c.CreateValidateCode(4);
                context.Session["varifyCode"] = code;

                c.CreateValidateGraphic(code, context);
            }
            else if (string.Compare(action, "loginInfo", false) == 0)
            {
                context.Response.ContentType = "application/json";
                LoginInfoData data = new LoginInfoData();

                int page  = int.Parse(context.Request["page"]);
                int limit = int.Parse(context.Request["limit"]);


                data.code  = 0;
                data.msg   = "ok";
                data.count = 6;

                List <LoginInfo> listInfo = new List <LoginInfo>();

                listInfo.Add(new LoginInfo()
                {
                    City      = "重庆",
                    Id        = 0,
                    Ip        = "192.168.1.1",
                    UserName  = "******",
                    LoginDate = "2020-6-10 19:00:00",
                    UserOS    = "win10"
                });
                listInfo.Add(new LoginInfo()
                {
                    City      = "重庆",
                    Id        = 1,
                    Ip        = "192.168.1.1",
                    UserName  = "******",
                    LoginDate = "2020-6-10 19:00:00",
                    UserOS    = "win10"
                });
                listInfo.Add(new LoginInfo()
                {
                    City      = "重庆",
                    Id        = 2,
                    Ip        = "192.168.1.1",
                    UserName  = "******",
                    LoginDate = "2020-6-10 19:00:00",
                    UserOS    = "win10"
                });
                listInfo.Add(new LoginInfo()
                {
                    City      = "重庆",
                    Id        = 3,
                    Ip        = "192.168.1.1",
                    UserName  = "******",
                    LoginDate = "2020-6-10 19:00:00",
                    UserOS    = "win10"
                });
                listInfo.Add(new LoginInfo()
                {
                    City      = "重庆",
                    Id        = 4,
                    Ip        = "192.168.1.1",
                    UserName  = "******",
                    LoginDate = "2020-6-10 19:00:00",
                    UserOS    = "win10"
                });
                listInfo.Add(new LoginInfo()
                {
                    City      = "重庆",
                    Id        = 5,
                    Ip        = "192.168.1.1",
                    UserName  = "******",
                    LoginDate = "2020-6-10 19:00:00",
                    UserOS    = "win10"
                });
                data.data = listInfo.Skip((page - 1) * limit).Take(limit).ToList();



                context.Response.Write(JsonConvert.SerializeObject(data));
            }
            else if (string.Compare(action, "notice", false) == 0)
            {
                context.Response.ContentType = "application/json";
                string p    = context.Request["page"];
                string l    = context.Request["limit"];
                int    page = -1;
                if (!string.IsNullOrEmpty(p))
                {
                    page = int.Parse(p);
                }
                int limit = -1;
                if (!string.IsNullOrEmpty(l))
                {
                    limit = int.Parse(l);
                }

                NoticeData data = new NoticeData();
                data.code = 0;
                data.msg  = "ok";
                var list = TestData.getNotice();
                if (page < 0 || limit < 0)
                {
                    data.data = list;
                }
                else
                {
                    data.data = list.Skip((page - 1) * limit).Take(limit).ToList();
                }
                data.count = list.Count();



                context.Response.Write(JsonConvert.SerializeObject(data));
            }
            else if (string.Compare(action, "article", false) == 0)
            {
                context.Response.ContentType = "application/json";
                string p    = context.Request["page"];
                string l    = context.Request["limit"];
                int    page = -1;
                if (!string.IsNullOrEmpty(p))
                {
                    page = int.Parse(p);
                }
                int limit = -1;
                if (!string.IsNullOrEmpty(l))
                {
                    limit = int.Parse(l);
                }

                ArticleData data = new ArticleData();
                data.code = 0;
                data.msg  = "ok";
                var list = TestData.GetArticle();
                if (page < 0 || limit < 0)
                {
                    data.data = list;
                }
                else
                {
                    data.data = list.Skip((page - 1) * limit).Take(limit).ToList();
                }
                data.count = list.Count();



                context.Response.Write(JsonConvert.SerializeObject(data));
            }
            else if (string.Compare(action, "uploadImg", false) == 0)
            {
                ImgJson iJson = new ImgJson();
                iJson.data = new List <string>();

                string dir         = "\\UpImgs\\" + DateTime.Now.ToString("yyyyMMdd");
                string physicsPath = HttpContext.Current.Server.MapPath("~" + dir);
                if (!System.IO.Directory.Exists(physicsPath))
                {
                    System.IO.Directory.CreateDirectory(physicsPath);
                }
                for (int i = 0; i < context.Request.Files.Count; i++)
                {
                    string phPath = string.Empty;
                    //获取上传的文件的对象
                    HttpPostedFile img = context.Request.Files[i];

                    //获取上传文件的名称
                    string s = img.FileName;
                    var    strFileExtension = s.Substring(s.LastIndexOf('.') + 1, s.Length - s.LastIndexOf('.') - 1);
                    string allowextension   = System.Configuration.ConfigurationManager.AppSettings["ImageType"];
                    if (allowextension.ToLower().IndexOf(strFileExtension.ToLower()) >= 0)
                    {
                        int    len      = s.LastIndexOf(".") - s.LastIndexOf("\\") - 1;
                        string fileName = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Millisecond.ToString();
                        string fullName = fileName + "." + strFileExtension;

                        //fileName = fileName.Replace(",", "");
                        //fullName = fullName.Replace(",", "");
                        //fullName = fullName.Replace(":", "");
                        //截取获得上传文件的名称(ie上传会把绝对路径也连带上,这里只得到文件的名称)
                        //string str = System.Guid.NewGuid().ToString("N")+ s.Substring(s.LastIndexOf(".") - 1); // s.Substring(s.LastIndexOf("\\") + 1);
                        string path = dir + "\\" + fullName;
                        phPath = physicsPath + "//" + fullName;
                        //保存文件
                        img.SaveAs(phPath);
                        iJson.data.Add(path);
                    }
                }
                if (iJson.data.Count > 0 && iJson.data.Count == context.Request.Files.Count)
                {
                    iJson.code = 1;
                }
                else
                {
                    iJson.code = 0;
                    iJson.msg  = "上传图片出现错误";
                }
                context.Response.ContentType = "application/json";
                context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                context.Response.Write(JsonConvert.SerializeObject(iJson));
            }
            else if (string.Compare(action, "uploadImg1", false) == 0)
            {
                context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");

                string fileType       = context.Request["dir"];
                string dir            = string.Empty;
                string allowextension = string.Empty;
                if (fileType == "file")
                {
                    dir            = "\\UpFiles\\" + DateTime.Now.ToString("yyyyMMdd");
                    allowextension = System.Configuration.ConfigurationManager.AppSettings["FileType"];
                }
                else
                {
                    dir            = "\\UpImgs\\" + DateTime.Now.ToString("yyyyMMdd");
                    allowextension = System.Configuration.ConfigurationManager.AppSettings["ImageType"];
                }
                try
                {
                    string physicsPath = HttpContext.Current.Server.MapPath("~" + dir);
                    if (!System.IO.Directory.Exists(physicsPath))
                    {
                        System.IO.Directory.CreateDirectory(physicsPath);
                    }
                    if (context.Request.Files.Count > 0)
                    {
                        string phPath = string.Empty;
                        //获取上传的文件的对象
                        HttpPostedFile img = context.Request.Files[0];

                        //获取上传文件的名称
                        string s = img.FileName;
                        var    strFileExtension = s.Substring(s.LastIndexOf('.') + 1, s.Length - s.LastIndexOf('.') - 1);

                        if (allowextension.ToLower().IndexOf(strFileExtension.ToLower()) >= 0)
                        {
                            int    len      = s.LastIndexOf(".") - s.LastIndexOf("\\") - 1;
                            string fileName = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Millisecond.ToString();
                            string fullName = fileName + "." + strFileExtension;

                            string path = dir + "\\" + fullName;
                            phPath = physicsPath + "//" + fullName;
                            string pp = path.Replace("\\", "/");
                            //保存文件
                            img.SaveAs(phPath);
                            context.Response.Write(JsonConvert.SerializeObject(new { error = 0, url = pp }));
                        }
                        else
                        {
                            context.Response.Write(JsonConvert.SerializeObject(new { error = 1, message = "文件格式不支持" }));
                        }
                    }
                    else
                    {
                        context.Response.Write(JsonConvert.SerializeObject(new { error = 1, message = "网络错误,后台没接收到文件" }));
                    }
                }
                catch (Exception)
                {
                    context.Response.Write(JsonConvert.SerializeObject(new { error = 1, message = "上传图片出错" }));
                    throw;
                }
            }
            else if (string.Compare(action, "noticeAE", false) == 0)
            {
                var      id      = context.Request["noticeId"];
                var      title   = context.Request["noticeTitle"];
                var      content = context.Request["noticeContent"];
                var      time    = context.Request["DataStart"];
                DateTime time1   = DateTime.Now;
                if (!string.IsNullOrEmpty(time))
                {
                    time1 = Convert.ToDateTime(time);
                }

                //编辑
                if (!string.IsNullOrEmpty(id))
                {
                }
                else
                {//新增
                }
                context.Response.Write(JsonConvert.SerializeObject(new { IsOk = "Ok", msg = "操作完成" }));
            }
            else if (string.Compare(action, "ArticleAE", false) == 0)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);

                if (ticket == null)
                {
                    context.Response.Write(JsonConvert.SerializeObject(new { IsOk = "NoOk", msg = "请刷新页面再试" }));
                    context.Response.End();
                }


                LLArticle article = new LLArticle();

                int    artId   = String.IsNullOrEmpty(context.Request["ArtId"]) ? -1 : int.Parse(context.Request["ArtId"]);
                string listStr = context.Request["ArtType"];

                if ("" != listStr && null != listStr)
                {
                    article.ArtType = listStr.Split(new char[] { ',' }).Select(str => int.Parse(str)).ToList();
                }


                article.Content = context.Request["Content"];
                article.Title   = context.Request["ArtTitle"];
                article.Digest  = context.Request["Digest"];
                article.ReadPwd = context.Request["ArtPwd"];
                article.Editor  = ticket.Name;
                if (artId > 0)
                {
                    article.LastUpdatetime = DateTime.Now;
                }
                else
                {
                    article.ArtTime = DateTime.Now;
                }
                context.Response.Write(JsonConvert.SerializeObject(new { IsOk = "Ok", msg = "操作成功" }));
            }
            else if (string.Compare(action, "articleType", false) == 0)
            {
                context.Response.ContentType = "application/json";
                string p    = context.Request["page"];
                string l    = context.Request["limit"];
                int    page = -1;
                if (!string.IsNullOrEmpty(p))
                {
                    page = int.Parse(p);
                }
                int limit = -1;
                if (!string.IsNullOrEmpty(l))
                {
                    limit = int.Parse(l);
                }

                ArtTypeData data = new ArtTypeData();
                data.code = 0;
                data.msg  = "ok";
                var list = TestData.GetLLType();
                if (page < 0 || limit < 0)
                {
                    data.data = list;
                }
                else
                {
                    data.data = list.Skip((page - 1) * limit).Take(limit).ToList();
                }
                data.count = list.Count();



                context.Response.Write(JsonConvert.SerializeObject(data));
            }
            else if (string.Compare(action, "artTypeAE", false) == 0)
            {
                var      id       = context.Request["TypeId"];
                var      title    = context.Request["TypeTitle"];
                var      detail   = context.Request["TypeDetail"];
                var      time     = context.Request["TypeCTime"];
                var      isHidden = context.Request["TypeIsHidden"];
                DateTime time1    = DateTime.Now;
                if (!string.IsNullOrEmpty(time))
                {
                    time1 = Convert.ToDateTime(time);
                }

                //编辑
                if (!string.IsNullOrEmpty(id))
                {
                }
                else
                {//新增
                }



                context.Response.Write(JsonConvert.SerializeObject(new { IsOk = "Ok", msg = "操作完成" }));
            }
        }
        public ImgJson SaveImages(HttpFileCollectionBase files, string uniqueImgFolderName, string categFolderName, ImgJson addToList = null, List <ImgSizeSetting> imgSizeList = null)
        {
            if (!CheckFilesExists(files))
            {
                return new ImgJson
                       {
                           CountHistory     = 0,
                           ImgJsonOrderList = new List <ImgJsonOrder>()
                       }
            }
            ;

            #region ImgSizeList
            imgSizeList = imgSizeList ?? new List <ImgSizeSetting> {
                GetImgSizeSetting(FULL_FILE_NAME_PREFIX),           // 1024x720 - full изображение с огрничением 1024x720
                GetImgSizeSetting(MIDDLE_FILE_NAME_PREFIX),         // 400x300 - для карточки объявления
                GetImgSizeSetting(SMALL_FILE_NAME_PREFIX),          // 200x150 - для горячих
                GetImgSizeSetting(SUPER_SMALL_FILE_NAME_PREFIX)     // 60x45 - для превью в карточке
            };
            #endregion

            var imgJson = addToList ?? new ImgJson {
                CountHistory = 0, ImgJsonOrderList = new List <ImgJsonOrder>()
            };
            var folderCategPath = CheckFolderAndCreate(Path.Combine(AdImagesFolder, categFolderName), true);
            var userFolderPath  = CheckFolderAndCreate(Path.Combine(AdImagesFolder, folderCategPath, uniqueImgFolderName), true);

            var imgLogo       = Image.FromFile(LogoPath);       // получаем файл логотипа
            var imgBackground = Image.FromFile(BackgroundPath); // получаем файл фонового изображения

            int maxWidth  = imgSizeList.Max(x => x.Width);      // Максимальный размер в настройках
            int maxHeight = imgSizeList.Max(x => x.Height);     // Минимальный размер в настройках


            ResultImage resultImage = new ResultImage();

            int indexName = 0;

            for (int i = 0; i < files.Count; i++)
            {
                Image resizedImg = null;

                try
                {
                    using (var fullImg = Image.FromStream(files[i].InputStream, useEmbeddedColorManagement: true, validateImageData: false))
                    {
                        resizedImg = ImgManager.ResizeImage(fullImg, ImageResizeMode.OnMinSide, maxWidth, maxHeight);
                    }
                }
                catch
                {
                    resizedImg?.Dispose();
                    files[i].InputStream?.Dispose();
                    continue;
                }


                files[i].InputStream?.Dispose();


                foreach (var e in imgSizeList)
                {
                    // предварительно уменьшаем изображение
                    resultImage.Bmp = (e.Width == maxWidth) && (e.Height == maxHeight)
                                        ? new Bitmap(ImgManager.ResizeImage(resizedImg, ImageResizeMode.OnMaxSide, e.Width, e.Height))
                                        : new Bitmap(ImgManager.ResizeImage(resizedImg, ImageResizeMode.OnMinSide, e.Width, e.Height));
                    resultImage.ImgRightSideShift  = resultImage.Bmp.Width;
                    resultImage.ImgBottomSideShift = resultImage.Bmp.Height;

                    #region proccessing
                    if (e.Width >= DEFAULT_CONTAINER_WIDTH)
                    {
                        int newLogoWidth;

                        if (e.Width == DEFAULT_CONTAINER_WIDTH)
                        {
                            // получаем изображение, вписанное в контейнер
                            resultImage  = ImgManager.CreateImageInContainer(resultImage.Bmp, ImageSizeChangeType.Inclose, imgBackground, e.Width, e.Height);
                            newLogoWidth = (int)((double)e.Width * 0.2);
                        }
                        else
                        {
                            newLogoWidth = (resultImage.Bmp.Width < resultImage.Bmp.Height)
                                         ? (int)((double)resultImage.Bmp.Height * 0.2)
                                         : (int)((double)resultImage.Bmp.Width * 0.2);
                        }


                        Image imgLogoWatermark = imgLogo;
                        if (imgLogo.Width > newLogoWidth)
                        {
                            double relation      = (double)imgLogo.Width / newLogoWidth;
                            int    newLogoHeight = (int)((double)imgLogo.Height / relation);
                            imgLogoWatermark = ImgManager.ResizeLogoImage(imgLogo, new Size(newLogoWidth, newLogoHeight));
                        }

                        resultImage.Bmp = ImgManager.CreateWatermark(resultImage, imgLogoWatermark);
                    }
                    else
                    {
                        resultImage = ImgManager.CreateImageInContainer(resultImage.Bmp, ImageSizeChangeType.Crop, null, e.Width, e.Height);
                    }
                    #endregion


                    //Получаем последний индекс в названии файла
                    indexName = imgJson.CreateIndexName(i);
                    //Путь и имя файла, что там сохранить его
                    var path = Path.Combine(userFolderPath, $"{indexName}-{e.Width}x{e.Height}.jpg");


                    resultImage.Bmp.Save(path, ImageFormat.Jpeg);
                    resultImage.Bmp.Dispose();
                }

                resizedImg.Dispose();

                imgJson.ImgJsonOrderList.Add(new ImgJsonOrder {
                    Order = indexName, IndexName = indexName
                });
            }

            imgLogo.Dispose();
            imgBackground.Dispose();


            imgJson.CountHistory = imgJson.GetMaxIndexNameInList();

            return(imgJson);
        }
 public ImgJson SaveImages(HttpFileCollectionBase files, string uniqueImgFolderName, long categFolderName, ImgJson addToList = null, List <ImgSizeSetting> imgSizeList = null)
 {
     return(SaveImages(files, uniqueImgFolderName, categFolderName.ToString(), addToList, imgSizeList));
 }
 public static string GetImgPath(long categFolderName, string folderImgName, ImgJson imgJsonObject, string imgSize = CONSTANT.MIDDLE_FILE_NAME_PREFIX)
 {
     return(GetImgPath(categFolderName.ToString(), folderImgName, imgJsonObject, imgSize));
 }
        /// <summary>
        /// Form image path
        /// </summary>
        /// <param name="categFolderName">Folder name of any ad</param>
        /// <param name="folderImgName">ad image name</param>
        /// <param name="imgJsonObject">ImgJson object with history and count</param>
        /// <param name="imgSize">Frefix name for images, use <see cref="CONSTANT"/> with param as 'MIDDLE_FILE_NAME_PREFIX'</param>
        /// <exception cref="NullReferenceException">
        ///     ImgJsonObject with type of<see cref="ImgJson"/> can't be null
        /// </exception>
        /// <returns>string</returns>
        public static string GetImgPath(string categFolderName, string folderImgName, ImgJson imgJsonObject, string imgSize = CONSTANT.MIDDLE_FILE_NAME_PREFIX)
        {
            if (imgJsonObject == null)
            {
                throw new NullReferenceException($"Check why {nameof(imgJsonObject)} comes with null");
            }

            string imgRootPathResult;

            if (!string.IsNullOrEmpty(folderImgName) && imgJsonObject.ImgJsonOrderList.Count > 0 && imgJsonObject.ImgJsonOrderList != null)
            {
                var defaultImgJson = imgJsonObject
                                     .ImgJsonOrderList
                                     .Where(e => e != null)
                                     .OrderBy(e => e.Order)
                                     .FirstOrDefault();

                int indexMainName = defaultImgJson?.IndexName ?? 0;

                imgRootPathResult = $@"/{CONSTANT.UPLOADS_IMG_FOLDER_NAME}/{CONSTANT.IMG_FOLDER_NAME}/{categFolderName}/{folderImgName}/{indexMainName + imgSize}.jpg";
            }
            else
            {
                imgRootPathResult = $@"/{CONSTANT.DEFAULT_NO_IMG_FULL_PATH}";
            }


            return(imgRootPathResult.Trim());
        }