Exemplo n.º 1
0
        public string InitializeDirectory(string folderToSaveTo = UploadFolder)
        {
            if (string.IsNullOrWhiteSpace(folderToSaveTo))
            {
                throw new ArgumentException(nameof(folderToSaveTo));
            }

            string serverMapPath = HttpServerUtilityBase?.MapPath(folderToSaveTo) ?? throw new ArgumentException(nameof(folderToSaveTo));

            if (!Directory.Exists(serverMapPath))
            {
                Directory.CreateDirectory(serverMapPath);
            }
            return(serverMapPath);
        }
Exemplo n.º 2
0
        public IEnumerable <Assembly> GetAssembliesInModules()
        {
            var possibleAssemblies = _fileSystem.DirectoryInfo
                                     .FromDirectoryName(_serverUtility.MapPath("~/Modules"))
                                     .GetFiles("*.dll", SearchOption.AllDirectories);

            foreach (var possibleAssm in  possibleAssemblies)
            {
                Assembly assembly = null;
                try
                {
                    assembly = Assembly.LoadFile(possibleAssm.FullName);
                }
                catch
                {
                    //nothing
                }

                if (assembly != null)
                {
                    yield return(assembly);
                }
            }
        }
Exemplo n.º 3
0
        public Response ProductSaveDatabase(Product ProductMd, HttpRequestBase Request, HttpServerUtilityBase Server, List <HttpPostedFileBase> postedFiles, out int ProductVid)
        {
            try
            {
                if (ProductMd.Id == 0)//Id 0 geliyorsa ilk kez ekleniyor demektir.
                {
                    int sort = 1;
                    int vid  = 1;
                    if (Count() != 0)
                    {
                        vid  = GetMax("Vid", "Product") + 1;
                        sort = GetMax("Sort", "Product") + 1;
                    }
                    ProductMd.Datetime = DateTime.Now;
                    ProductMd.Flag     = status.active;
                    ProductMd.Vid      = vid;
                    ProductVid         = vid;
                    ProductMd.Sort     = sort;
                    ProductMd.Url      = stringformatter.OnlyEnglishChar(ProductMd.ProductName + DateTime.Now.ToString("MMssyyhhddmm"));
                    ProductMd.ByWhoId  = AuthBLL.GetUser().Id;
                    InsertOrUpdate(ProductMd, ProductMd.Id);
                    Save();


                    string productname = stringformatter.OnlyEnglishChar(ProductMd.ProductName);
                    controlfiles.directory("~/public/upload/img/" + productname);

                    string path           = "";
                    string uzantisiz      = "";
                    string uzanti         = "";
                    var    supportedTypes = new[] { ".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG" };
                    var    RequestPhotos  = Request.Files["Photo"];
                    if (RequestPhotos != null && RequestPhotos.ContentLength > 0)
                    {
                        foreach (HttpPostedFileBase file in postedFiles)
                        {
                            uzantisiz = stringformatter.OnlyEnglishChar(Path.GetFileNameWithoutExtension(file.FileName));
                            uzanti    = Path.GetExtension(file.FileName);
                            string pathUzantsiz = Path.Combine(Server.MapPath("~/public/upload/img/" + productname), uzantisiz);
                            path = Path.Combine(Server.MapPath("~/public/upload/img/" + productname), uzantisiz + uzanti);
                            if (!supportedTypes.Contains(uzanti))
                            {
                                string ErrorMessage = "Yüklemeye Çalıştığunız Dosya Uzantısı Geçerli Değil - Sadece JPEG/JPG/PNG Geçerli";
                                return(responseBLL.create(false, ErrorMessage, null));
                            }
                            #region PhotoSaving
                            Photos PhotoMd = new Photos();
                            int    sortP   = 1;
                            int    vidP    = 1;
                            if (_photos.Count() != 0)
                            {
                                vidP  = GetMax("Vid", "Photos") + 1;
                                sortP = GetMax("Sort", "Photos") + 1;
                            }
                            PhotoMd.Datetime = DateTime.Now;
                            PhotoMd.Flag     = status.active;
                            PhotoMd.Vid      = vidP;
                            PhotoMd.Sort     = sortP;
                            PhotoMd.Url      = stringformatter.OnlyEnglishChar(uzantisiz + DateTime.Now.ToString("MMssyyhhddmm"));
                            int  j        = 1;
                            bool Pbulundu = false;
                            do
                            {
                                if (System.IO.File.Exists(path))
                                {
                                    path = pathUzantsiz + "(" + j + ")" + uzanti;
                                    j++;
                                }
                                else
                                {
                                    file.SaveAs(path);
                                    Pbulundu = true;
                                }
                            } while (!Pbulundu);

                            if (j != 1)
                            {
                                j--;
                                PhotoMd.Path = "/public/upload/img/" + productname + "/" + uzantisiz + "(" + j + ")" + uzanti;
                            }
                            else
                            {
                                PhotoMd.Path = "/public/upload/img/" + productname + "/" + uzantisiz + uzanti;
                            }

                            PhotoMd.ProductId = GetFirstOrDefault(f => f.Vid == vid).Id;
                            _photos.InsertOrUpdate(PhotoMd, PhotoMd.Id);
                            _photos.Save();
                            #endregion
                        }
                    }
                    else
                    {
                        return(responseBLL.create(true, "Ürün eklendi. Ancak Fotoğraf yüklenmedi.", null));
                    }

                    return(responseBLL.create(true, "Ürün eklendi.", null));
                }
                else //0 gelmiyorsa ilgili model güncelleniyor demektir.
                {
                    string url = Request["Product_url"];
                    ProductVid    = ProductMd.Vid;
                    ProductMd.Url = url;
                    Save();
                    string productname = stringformatter.OnlyEnglishChar(ProductMd.ProductName);
                    controlfiles.directory("~/public/upload/img/" + productname);
                    string path           = "";
                    string uzantisiz      = "";
                    string uzanti         = "";
                    var    supportedTypes = new[] { ".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG" };
                    var    RequestPhotos  = Request.Files["Photo"];
                    if (RequestPhotos != null && RequestPhotos.ContentLength > 0)
                    {
                        foreach (HttpPostedFileBase file in postedFiles)
                        {
                            uzantisiz = stringformatter.OnlyEnglishChar(Path.GetFileNameWithoutExtension(file.FileName));
                            uzanti    = Path.GetExtension(file.FileName);
                            string pathUzantsiz = Path.Combine(Server.MapPath("~/public/upload/img/" + productname), uzantisiz);
                            path = Path.Combine(Server.MapPath("~/public/upload/img/" + productname), uzantisiz + uzanti);
                            if (!supportedTypes.Contains(uzanti))
                            {
                                string ErrorMessage = "Yüklemeye Çalıştığunız Dosya Uzantısı Geçerli Değil - Sadece JPEG/JPG/PNG Geçerli";
                                return(responseBLL.create(false, ErrorMessage, null));
                            }

                            #region PhotoSaving
                            Photos PhotoMd = new Photos();
                            int    sortP   = 1;
                            int    vidP    = 1;
                            if (_photos.Count() != 0)
                            {
                                vidP  = GetMax("Vid", "Photos") + 1;
                                sortP = GetMax("Sort", "Photos") + 1;
                            }
                            PhotoMd.Datetime = DateTime.Now;
                            PhotoMd.Flag     = status.active;
                            PhotoMd.Vid      = vidP;
                            PhotoMd.Sort     = sortP;
                            PhotoMd.Url      = stringformatter.OnlyEnglishChar(uzantisiz + DateTime.Now.ToString("MMssyyhhddmm"));
                            int  j         = 1;
                            bool pathexist = false;
                            do
                            {
                                if (System.IO.File.Exists(path))
                                {
                                    path = pathUzantsiz + "(" + j + ")" + uzanti;
                                    j++;
                                }
                                else
                                {
                                    file.SaveAs(path);
                                    pathexist = true;
                                }
                            } while (!pathexist);

                            if (j != 1)
                            {
                                j--;
                                PhotoMd.Path = "/public/upload/img/" + productname + "/" + uzantisiz + "(" + j + ")" + uzanti;
                            }
                            else
                            {
                                PhotoMd.Path = "/public/upload/img/" + productname + "/" + uzantisiz + uzanti;
                            }
                            PhotoMd.ProductId = GetFirstOrDefault(f => f.Url == url).Id;
                            _photos.InsertOrUpdate(PhotoMd, PhotoMd.Id);
                            _photos.Save();
                            #endregion
                        }
                    }

                    else
                    {
                        return(responseBLL.create(true, "Ürün güncellendi. Fotoğraf yüklenmedi.", null));
                    }

                    return(responseBLL.create(true, "Ürün güncellendi.", null));
                }
            }

            catch (Exception ex)
            {
                ProductVid = 0;
                return(responseBLL.create(false, "Ürün eklenirken bir hata oluştu. Lütfen tekrar deneyiniz.", null));
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Returns the path to the parent directory on the application file server.
 /// </summary>
 /// <param name="server"> The running web server. </param>
 /// <returns> The path to the parent directory on the application file server. /returns>
 internal static string GetFileServerPath(HttpServerUtilityBase server = null)
 {
     return(server != null
         ? server.MapPath(@"~\App_Data\")
         : AppDomain.CurrentDomain.BaseDirectory + @"App_Data\");
 }
        public static void ResponseNotification(ResponseVM response, string responsible, PortalContext db, HttpServerUtilityBase server)
        {
            foreach (var update in response.Updates)
            {
                update.RefundItem = db.RefundItems.First(r => r.RefundItemID == update.RefundItemID);
            }
            var mailer = new UserMailer();

            if (response.Updates.Length == 0 || response.Updates.All(u => u.Status == RefundItemStatus.REJECTED_NO_APPEAL))
            {
                return;
            }
            switch (response.OwnerType)
            {
            case ResponseOwnerType.EVENT:
                var @event = db.Events.Find(response.OwnerID);
                foreach (var manager in @event.Freelancer.Managers)
                {
                    mailer.EventResponseNotification(
                        manager.RefundProfile.User.ContactInfo.Email,
                        "Manager",
                        responsible,
                        @event,
                        response.Updates,
                        server.MapPath("~/Content/images/logo-wella.png")
                        ).Send();
                }

                break;

            case ResponseOwnerType.VISIT:
                var visit = db.Visits.Find(response.OwnerID);
                foreach (var manager in visit.Freelancer.Managers)
                {
                    mailer.VisitResponseNotification(
                        manager.RefundProfile.User.ContactInfo.Email,
                        "Manager",
                        responsible,
                        visit,
                        response.Updates,
                        server.MapPath("~/Content/images/logo-wella.png")
                        ).Send();
                }
                break;

            case ResponseOwnerType.MONTHLY:
                var monthly = db.Monthlies.Find(response.OwnerID);
                foreach (var manager in monthly.Freelancer.Managers)
                {
                    mailer.MonthlyResponseNotification(
                        manager.RefundProfile.User.ContactInfo.Email,
                        "Manager",
                        responsible,
                        monthly,
                        response.Updates,
                        server.MapPath("~/Content/images/logo-wella.png")
                        ).Send();
                }
                break;
            }
        }
Exemplo n.º 6
0
 public SimplePasswordService(HttpServerUtilityBase server, Cache cache)
     : base(server.MapPath("~/App_Data/simplepassword.txt"), cache)
 {
 }
 public void UploadStaticPageImage(HttpPostedFileBase originalImage, string rootPath, string imagePrefix, HttpServerUtilityBase server)
 {
     originalImage.SaveAs(server.MapPath("~/" + rootPath + imagePrefix + originalImage.FileName));
 }
 public DocumentTypeThumbnailFileResolver(HttpServerUtilityBase server, RebelSettings settings, UrlHelper url)
     : base(new DirectoryInfo(server.MapPath(settings.RebelFolders.DocTypeThumbnailFolder)), url)
 {
 }
Exemplo n.º 9
0
 public static string GetServerRoot(
     HttpServerUtilityBase server)
 {
     return(server.MapPath(@"\"));
 }
Exemplo n.º 10
0
 /// <summary>
 /// Get al List of paths for album´s download purposes
 /// </summary>
 /// <param name="id">Album identity</param>
 /// <param name="server">Server base</param>
 /// <returns>The list of urls</returns>
 public string[] GetImagePathsForDownload(int id, HttpServerUtilityBase server)
 {
     return(ImageRepository.Get(im => im.AlbumId == id).Select(im => server.MapPath(im.Path)).ToArray());
 }
Exemplo n.º 11
0
        /// <summary>
        /// Upload a list of Images to the server
        /// </summary>
        /// <param name="files">Files to Upload</param>
        /// <param name="server">Server base</param>
        /// <param name="request">Request base</param>
        /// <param name="albumid">The album of the Images</param>
        /// <returns>Files uploaded</returns>
        public object UploadFileToServer(ICollection <HttpPostedFileBase> files, HttpServerUtilityBase server, HttpRequestBase request, int?albumid)
        {
            int fileUploadedCount = 0;

            string[] filesUploaded = new string[request.Files.Count];
            int      i             = 0;

            foreach (var file in files)
            {
                if ((file != null) && (file.ContentLength > 0))
                {
                    string imagepath;
                    string thumbnailpath;
                    Guid   unique = Guid.NewGuid();
                    if (file.FileName.ToUpper().Contains("JPG") || file.FileName.ToUpper().Contains("JPEG") || file.FileName.ToUpper().Contains("GIF") || file.FileName.ToUpper().Contains("PNG"))
                    {
                        Album album;
                        if (albumid == null)
                        {
                            album = AlbumRepository.Get(a => a.Name == Resources.AppMessages.Default_Album_Name).FirstOrDefault();
                            if (album == null)
                            {
                                album = new Album {
                                    Name = Resources.AppMessages.Default_Album_Name, Description = Resources.AppMessages.Default_Album_Description, IsPublic = true, DateCreated = DateTime.Now
                                };
                                AlbumRepository.Insert(album);
                                AlbumRepository.UnitOfWork.Commit();;
                                AlbumRepository.Get(a => a.Name == album.Name);
                            }
                            albumid = album.AlbumId;
                        }
                        else
                        {
                            album = AlbumRepository.GetByID(albumid);
                        }
                        CheckDirectoryForAlbum(albumid, server);
                        WebImage image = new WebImage(file.InputStream);
                        imagepath = "~/Content/Images/" + albumid + "/" + unique + "_" + file.FileName;
                        image.Resize(1024, 768, preserveAspectRatio: true, preventEnlarge: true)
                        .Crop(1, 1)
                        .Save(server.MapPath(imagepath));
                        thumbnailpath = "~/Content/Images/Thumbnails/" + albumid + "/" + unique + "_" + file.FileName;
                        image.Resize(Int32.Parse(BgResources.Media_ThumbnailWidth), Int32.Parse(BgResources.Media_ThumbnailHeight), preserveAspectRatio: true, preventEnlarge: true)
                        .Crop(1, 1)
                        .Save(server.MapPath(thumbnailpath));
                        ImageRepository.Insert(new Image {
                            Name = file.FileName, Path = imagepath, ThumbnailPath = thumbnailpath, Album = album, DateCreated = DateTime.Now, FileName = file.FileName
                        });
                        ImageRepository.UnitOfWork.Commit();
                        fileUploadedCount++;
                        filesUploaded[i] = file.FileName;
                    }
                    else
                    {
                        file.SaveAs(server.MapPath("~/Content/Files/" + unique + "_" + file.FileName));
                        fileUploadedCount++;
                        filesUploaded[i] = file.FileName;
                    }
                }
                i++;
            }
            var result = new
            {
                fileCount = fileUploadedCount,
                files     = filesUploaded
            };

            return(result);
        }
Exemplo n.º 12
0
 /// <summary>
 /// Converts a path from an application relative path (~/...) to a full filesystem path
 /// </summary>
 /// <param name="relativePath">App-relative path of the file</param>
 /// <returns>Full path of the file</returns>
 public override string MapPath(string relativePath)
 {
     return(_serverUtility.MapPath(relativePath));
 }
Exemplo n.º 13
0
 private string GetServerSideFullname(string filename)
 {
     return(Path.Combine(_server.MapPath("/" + _root), filename));
 }
Exemplo n.º 14
0
 public string GetPath(Site site)
 {
     return(_server.MapPath($"~/App_Data/sitemap-{site.Id}.xml"));
 }
Exemplo n.º 15
0
        public static Guid GetFileHash(string fname, HttpServerUtilityBase server)
        {
            var localPath = server.MapPath(fname.Replace('/', '\\'));

            return(GetFileHash(localPath));
        }
Exemplo n.º 16
0
        public static string MergeImages(HttpServerUtilityBase Server, string backImagePath, string frontImagePath, string facebookId, string type)
        {
            string pathRoute = SiteSettings.MergeImageRoute;

            Image backImage = null;

            //IF USE PROXY
            //WebRequest request = HttpWebRequest.Create(backImagePath);
            //WebProxy proxy = new System.Net.WebProxy(SiteSettings.ProxyServerIP, true);
            //proxy.Credentials = new System.Net.NetworkCredential(SiteSettings.ProxyUserName, SiteSettings.ProxyPass);
            //request.Proxy = proxy;
            //Stream backImageStream = request.GetResponse().GetResponseStream();

            using (Stream backImageStream = HttpWebRequest.Create(backImagePath).GetResponse().GetResponseStream())
            {
                try
                {
                    backImage = Image.FromStream(backImageStream);
                }
                catch (Exception ex)
                {
                    Common.Helper.CommonFunction.LogToFile(ex.InnerException != null ? ex.InnerException.Message : ex.Message, "Stream backImageStream", Server);
                }
                if (type == Constants.USERTYPE_TWITTER || backImage.Width < 100)
                {
                    double aspectRatio = (double)backImage.Width / (double)backImage.Height;
                    int    newWidth    = 190;
                    int    newHeight   = (int)Math.Round(newWidth / aspectRatio);
                    backImage = new Bitmap(backImage, newWidth, newHeight);
                }
                Bitmap frontImage = null;
                try
                {
                    frontImage = (Bitmap)Image.FromFile(Server.MapPath(frontImagePath));
                }
                catch (Exception ex)
                {
                    Common.Helper.CommonFunction.LogToFile(ex.InnerException != null ? ex.InnerException.Message : ex.Message, "get frontImage", Server);
                }

                try
                {
                    using (var bitmap = new Bitmap(backImage.Width, backImage.Height))
                    {
                        using (var canvas = Graphics.FromImage(bitmap))
                        {
                            canvas.InterpolationMode = InterpolationMode.HighQualityBilinear;
                            if (type == Constants.USERTYPE_TWITTER)
                            {
                                canvas.DrawImage(backImage, new Rectangle(0, 0, backImage.Width, backImage.Height));//, new Rectangle(0, 0, backImage.Width, backImage.Height), GraphicsUnit.Pixel);
                                canvas.DrawImage(frontImage, new Rectangle(backImage.Width - frontImage.Width, backImage.Height - frontImage.Height, frontImage.Width, frontImage.Height));
                            }
                            else
                            {
                                canvas.DrawImage(backImage, new Rectangle(0, 0, backImage.Width, backImage.Height));//, new Rectangle(0, 0, backImage.Width, backImage.Height), GraphicsUnit.Pixel);
                                canvas.DrawImage(frontImage, new Rectangle(backImage.Width - frontImage.Width, backImage.Height - frontImage.Height, frontImage.Width, frontImage.Height));
                            }
                            canvas.Save();
                        }

                        string fileName = facebookId + ".png";
                        bitmap.Save(Server.MapPath(pathRoute) + fileName, ImageFormat.Png);


                        double aspectRatio = (double)bitmap.Width / (double)bitmap.Height;
                        int    newWidth    = 24;
                        int    newHeight   = (int)Math.Round(newWidth / aspectRatio);
                        var    miniImage   = new Bitmap(bitmap, newWidth, newHeight);

                        miniImage.Save(Server.MapPath(SiteSettings.MergeImageRoute.Replace("avatar", "miniavatar")) + fileName, ImageFormat.Png);


                        backImage.Dispose();
                        frontImage.Dispose();
                        bitmap.Dispose();
                        miniImage.Dispose();

                        return(pathRoute + fileName);
                    }
                }
                catch (Exception ex)
                {
                    Common.Helper.CommonFunction.LogToFile(ex.InnerException != null ? ex.InnerException.Message : ex.Message, "Merging Image And Save Image", Server);
                    return(string.Empty);
                }
            }
        }
Exemplo n.º 17
0
        public static UploadImageResult UploadImage(HttpPostedFileBase image, HttpServerUtilityBase server, int articleId, string article_state)
        {
            var result = new UploadImageResult {
                Success = false
            };
            string path              = "/Content/images/articles/";
            int    maxSize           = 300000;
            string allowedExtensions = "jpg,png,bmp,gif,jpeg";
            string imagePath         = string.Empty;

            if (image == null || image.ContentLength == 0)
            {
                result.Errors.Add("You didn't select a image file or the file you uploaded was invalid.");
                return(result);
            }

            // Check image size
            if (image.ContentLength > maxSize)
            {
                result.Errors.Add("Image was larger than the maximum upload size.Max image size allowed is 256KB.");
            }

            // Check image extension
            var extension = Path.GetExtension(image.FileName).Substring(1).ToLower();

            if (!allowedExtensions.Contains(extension))
            {
                result.Errors.Add("Only image files can be uploaded with extension. jpg,png,bmp,gif,jpeg");
            }

            // If there are no errors save image
            if (!result.Errors.Any())
            {
                // update image to db
                var             newName    = "";
                var             serverPath = "";
                DataAccessLayer datalayer  = null;

                //add image to repository
                newName    = articleId + "." + extension;
                serverPath = server.MapPath("~" + path + newName);
                image.SaveAs(serverPath);
                result.ImagePath = "../../Content/images/articles/" + newName;

                //update image to db
                //dataAccess = new DataAccessLayer();
                imagePath = result.ImagePath;
                datalayer = new DataAccessLayer();
                if (article_state == "published")
                {
                    datalayer.UpdateArticlePublishedImage(articleId, imagePath);
                }
                else if (article_state == "entry")
                {
                    datalayer.UpdateArticleEntryImage(articleId, imagePath);
                }


                result.Success = true;
            }

            return(result);
        }
Exemplo n.º 18
0
 public IList <string> GetAllImagesForArticleFromLocal(HttpServerUtilityBase server)
 {
     return(Directory.GetFiles(server.MapPath(String.Format("{0}ArticleImage/Images120", repoConfig.Get(ConfigurationKeyStatic.CONTENT_EXTERNAL_URL)))).ToList <string>());;
 }
Exemplo n.º 19
0
        public string TemporaryAvatarDAL(HttpPostedFile tempAvatar, HttpServerUtilityBase localServer, int userID)
        {
            try
            {
                if (tempAvatar == null)
                {
                    throw new ArgumentNullException("Debe elegir una imágen.");
                }

                string imgDir;
                using (var context = new WinNotesEntities())
                {
                    imgDir = "/Content/Temp/" + context.Person.Where(p => p.PersonID == userID).Single().UserName;
                }

                Directory.CreateDirectory(localServer.MapPath(imgDir));
                string imgFullPath = localServer.MapPath(imgDir) + "/" + tempAvatar.FileName;

                // Get file data
                byte[] data = new byte[] { };
                using (var binaryReader = new BinaryReader(tempAvatar.InputStream))
                {
                    data = binaryReader.ReadBytes(tempAvatar.ContentLength);
                }

                // Guardar imagen en el servidor
                using (FileStream image = File.Create(imgFullPath, data.Length))
                {
                    image.Write(data, 0, data.Length);
                }

                // Verifica si la imágen cumple las condiciones de validación
                const int     _maxSize   = 2 * 1024 * 1024;
                const int     _maxWidth  = 1000;
                const int     _maxHeight = 1000;
                List <string> _fileTypes = new List <string>()
                {
                    "jpg", "jpeg", "gif", "png"
                };
                string fileExt = Path.GetExtension(tempAvatar.FileName);

                if (new FileInfo(imgFullPath).Length > _maxSize)
                {
                    throw new FormatException("El avatar no debe superar los 2mb.");
                }

                if (!_fileTypes.Contains(fileExt.Substring(1), StringComparer.OrdinalIgnoreCase))
                {
                    throw new FormatException("Para el avatar solo se admiten imágenes JPG, JPEG, GIF Y PNG.");
                }

                using (Image img = Image.FromFile(imgFullPath))
                {
                    if (img.Width > _maxWidth || img.Height > _maxHeight)
                    {
                        throw new FormatException("El avatar admite hasta una resolución de 1000x1000.");
                    }
                }

                return(imgDir + "/" + tempAvatar.FileName);
            }
            catch
            {
                throw;
            }
        }
Exemplo n.º 20
0
 public static string GetFontPath(HttpServerUtilityBase server)
 {
     return(server.MapPath(PDF_FONT_NAME));
 }
Exemplo n.º 21
0
        /// <summary>
        /// Uploading and resizing an image, Currently it is used to upload member profile pic, provider service banner image and category image
        /// </summary>
        /// <param name="originalImage"></param>
        /// <param name="imagePrefix"></param>
        /// <param name="rootPath"></param>
        /// <param name="server"></param>
        /// <param name="_unitOfWork"></param>
        /// <param name="memberId"></param>
        /// <param name="serviceId"></param>
        public void UploadImage(HttpPostedFileBase originalImage, string imagePrefix, string rootPath, HttpServerUtilityBase server, GenericUnitOfWork _unitOfWork, int memberId, int productId = 0, int categoryId = 0)
        {
            bool existsOriginal = System.IO.Directory.Exists(server.MapPath("~/" + rootPath + "Original/"));

            if (!existsOriginal)
            {
                System.IO.Directory.CreateDirectory(server.MapPath("~/" + rootPath + "Original/"));
            }
            originalImage.SaveAs(server.MapPath("~/" + rootPath + "Original/" + imagePrefix + originalImage.FileName));
            // Large size for service banner image
            if (productId != 0)
            {
                WebImage img1 = new WebImage(server.MapPath("~/" + rootPath + "Original/" + imagePrefix + originalImage.FileName));
                img1.Resize(849, 320);
                bool exists = System.IO.Directory.Exists(server.MapPath("~/" + rootPath + "Large/"));
                if (!exists)
                {
                    System.IO.Directory.CreateDirectory(server.MapPath("~/" + rootPath + "Large/"));
                }
                img1.Save(Path.Combine(server.MapPath("~/" + rootPath + "Large/" + imagePrefix + originalImage.FileName)));
            }

            WebImage img2 = new WebImage(server.MapPath("~/" + rootPath + "Original/" + imagePrefix + originalImage.FileName));

            img2.Resize(274, 175);
            bool exists2 = System.IO.Directory.Exists(server.MapPath("~/" + rootPath + "Medium/"));

            if (!exists2)
            {
                System.IO.Directory.CreateDirectory(server.MapPath("~/" + rootPath + "Medium/"));
            }
            img2.Save(Path.Combine(server.MapPath("~/" + rootPath + "Medium/" + imagePrefix + originalImage.FileName)));

            WebImage img3 = new WebImage(server.MapPath("~/" + rootPath + "Original/" + imagePrefix + originalImage.FileName));

            img3.Resize(68, 68);
            bool exists3 = System.IO.Directory.Exists(server.MapPath("~/" + rootPath + "Small/"));

            if (!exists3)
            {
                System.IO.Directory.CreateDirectory(server.MapPath("~/" + rootPath + "Small/"));
            }
            img3.Save(Path.Combine(server.MapPath("~/" + rootPath + "Small/" + imagePrefix + originalImage.FileName)));

            System.IO.File.Delete(server.MapPath("~/" + rootPath + "Original/" + imagePrefix + originalImage.FileName));
        }
Exemplo n.º 22
0
        public static void FileDelete(HttpServerUtilityBase server, string imageName)
        {
            var folder = server.MapPath("~/CmsFiles/" + imageName);

            System.IO.File.Delete(folder);
        }
Exemplo n.º 23
0
 public static string GetRootFolder(HttpServerUtilityBase server, string empresa, string bd)
 {
     return(server.MapPath(Path.Combine(ConfigurationManager.AppSettings["RootFolderFicheros"], bd, empresa)));
 }
Exemplo n.º 24
0
    public PDFCreator(List <System.Web.UI.WebControls.ListItem> items, string totaalPrijs, HttpResponseBase response, HttpServerUtilityBase server)
    {    // Create a Document object
        var document = new Document(PageSize.A4, 50, 50, 25, 25);


        // Create a new PdfWrite object, writing the output to a MemoryStream
        var output = new MemoryStream();
        var writer = PdfWriter.GetInstance(document, output);

        // Open the Document for writing
        document.Open();

        // Read in the contents of the Receipt.htm HTML template file
        string contents = File.ReadAllText(server.MapPath("~/HTMLTemplate/Receipt.htm"));

        // Replace the placeholders with the user-specified text
        contents = contents.Replace("[TOTALPRICE]", Convert.ToDecimal(totaalPrijs).ToString("c"));
        contents = contents.Replace("[ORDERDATE]", DateTime.Now.ToShortDateString());

        var itemsTable = @"<table><tr><th style=""font-weight: bold"">Naam</th><th style=""font-weight: bold"">Prijs</th></tr>";

        foreach (System.Web.UI.WebControls.ListItem item in items)
        {
            // Each CheckBoxList item has a value of ITEMNAME|ITEM#|QTY, so we split on | and pull these values out...
            var pieces = item.Value.Split("|".ToCharArray());
            if (pieces[0] == string.Empty || pieces[0].Length < 3)
            {
                continue;
            }
            if (pieces[1] == " 0" || pieces[1] == string.Empty)
            {
                pieces[1] = "-";
            }
            else
            {
                pieces[1] = "€" + pieces[1];
            }

            itemsTable += string.Format("<tr><td>{0}</td><td>{1}</td></tr>",
                                        pieces[0], pieces[1]);
        }

        itemsTable += "</table>";

        contents = contents.Replace("[ITEMS]", itemsTable);


        var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);

        foreach (var htmlElement in parsedHtmlElements)
        {
            document.Add(htmlElement as IElement);
        }

        // You can add additional elements to the document. Let's add an image in the upper right corner
        //var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/4guysfromrolla.gif"));
        //logo.SetAbsolutePosition(440, 800);
        //document.Add(logo);

        document.Close();

        response.ContentType = "application/pdf";
        response.AddHeader("Content-Disposition", string.Format("attachment;filename=Receipt-{0}.pdf", "5"));
        response.BinaryWrite(output.ToArray());
    }
        public static byte[] GetMapImage(HttpServerUtilityBase server, MapExportModel model, string qgisPath, string pythonPath)
        {
            var tempPath       = server.MapPath(FileSystemManager.GetTempDirectoryPath());
            var baseLayerPath  = server.MapPath("~/Content/MapExport/baseLayer.geojson");
            var concernedFiles = new List <string>();

            byte[]  exportFileData = null;
            Process process        = null;
            string  stdoutx        = null;
            string  stderrx        = null;

            try
            {
                FileSystemManager.EnsureFolderExists(tempPath);

                var sb = new StringBuilder();

                //Init python script
                InitScript(sb, qgisPath, model.MapExtent);

                //Add base layer
                AddLayer(sb, baseLayerPath, "Baselayer", 255, false, false, new MapExportModel.LegendItem[] { new MapExportModel.LegendItem {
                                                                                                                  Color = "#FAFAFA", Name = "Sweden"
                                                                                                              } });

                //Make sure layers are sorted by z-index
                model.Layers = model.Layers.OrderBy(l => l.Zindex).ToArray();

                //Add all other layers
                foreach (var layer in model.Layers)
                {
                    //Create file path
                    var layerFilePath = FileSystemManager.CombinePathAndFilename(tempPath,
                                                                                 FileSystemManager.CreateRandomFilename(".geojson"));
                    concernedFiles.Add(layerFilePath);

                    //Save layer geojson in temp file
                    FileSystemManager.CreateTextFile(layerFilePath, layer.GeoJson);

                    //Add layer to script
                    AddLayer(sb, layerFilePath, layer.Name.ReplaceSwedishChars().RemoveNonAscii(), layer.Occupancy, layer.IsPointLayer, true, layer.Legends, layer.Attribute);
                }

                //Create temp output path
                var outputFilePath = FileSystemManager.CombinePathAndFilename(tempPath,
                                                                              FileSystemManager.CreateRandomFilename(".png"));
                concernedFiles.Add(outputFilePath);

                //Finalize script
                FinalizeScript(sb, model.Dpi, outputFilePath);

                //Create python script path
                var pythonScriptPath = FileSystemManager.CombinePathAndFilename(tempPath,
                                                                                FileSystemManager.CreateRandomFilename(".py"));
                concernedFiles.Add(pythonScriptPath);

                //Temporaly save script file
                FileSystemManager.CreateTextFile(pythonScriptPath, sb.ToString());

                var command   = string.Format("{0}\\python", pythonPath);
                var arguments = pythonScriptPath;

                //Create new process
                process = new Process()
                {
                    StartInfo = new ProcessStartInfo()
                    {
                        Arguments        = arguments,
                        CreateNoWindow   = true,
                        FileName         = command,
                        UseShellExecute  = false,
                        WorkingDirectory = pythonPath
                    }
                };
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;

                //Start process
                process.Start();

                //Wait max 1 min to execute
                var timeout = TimeSpan.FromMinutes(1);
                stdoutx = process.StandardOutput.ReadToEnd();
                stderrx = process.StandardError.ReadToEnd();
                if (process.WaitForExit((int)timeout.TotalMilliseconds))  // wait max 1 minutes.
                {
                    exportFileData = System.IO.File.ReadAllBytes(outputFilePath);
                }
                else // timeout
                {
                    process.Kill();
                    throw new Exception("Python process Timeout");
                }
            }
            catch
            {
                if (process != null)
                {
                    Debug.WriteLine("QGIS Map generation Exit code : {0}", process.ExitCode);
                    Debug.WriteLine("QGIS Map generation Stdout : {0}", stdoutx);
                    Debug.WriteLine("QGIS Map generation Stderr : {0}", stderrx);
                }

                //Clean up
                if (process != null && !process.HasExited)
                {
                    process.Kill();
                }
            }
            finally
            {
                //Remove all files created in this method
                foreach (var concernedFile in concernedFiles)
                {
                    FileSystemManager.DeleteFile(concernedFile);
                }
            }

            return(exportFileData);
        }
Exemplo n.º 26
0
        /* 1.上傳檔案
         * 2.抓出資料/刪除檔案
         * 3.匯入資料到sql server
         *
         *
         *
         * */
        public string import(HttpPostedFileBase fileuploadExcel, HttpServerUtilityBase Server)
        {
            //上傳檔案
            string filename     = "";
            string fullFilename = "";

            if (fileuploadExcel != null && fileuploadExcel.ContentLength > 0)
            {
                filename = Path.GetFileName(fileuploadExcel.FileName);
                string picExten = System.IO.Path.GetExtension(filename);
                filename     = DateTime.Now.ToString("yyyyMMddhhmmss") + picExten;
                fullFilename = Path.Combine(Server.MapPath("~/Content/uploads"), filename);
                fileuploadExcel.SaveAs(fullFilename);
            }



            //抓出Excel資料
            var sData = new LinqToExcel.ExcelQueryFactory(fullFilename);
            var rows  = (from row in sData.Worksheet("Sheet1") select row).ToList();

            DataTable dt = new DataTable();

            //



            dt.Columns.Add("DateX");
            dt.Columns.Add("dat");
            dt.Columns.Add("lonX");
            dt.Columns.Add("chll");
            dt.Columns.Add("sa");
            dt.Columns.Add("cerrentX");
            dt.Columns.Add("cerrentY");
            dt.Columns.Add("waveh");
            dt.Columns.Add("tide");
            dt.Columns.Add("uv");
            foreach (var item in rows)
            {
                DataRow dr = dt.NewRow();
                dr["DateX"]    = item[0];
                dr["dat"]      = item[1];
                dr["lonX"]     = item[2];
                dr["chll"]     = item[3];
                dr["sa"]       = item[4];
                dr["cerrentX"] = item[5];
                dr["cerrentY"] = item[6];
                dr["waveh"]    = item[7];
                dr["tide"]     = item[8];
                dr["uv"]       = item[9];
                dt.Rows.Add(dr);
            }



            //匯入資料到暫存table
            string BStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            try
            {
                SqlConnection Bulkcn = new SqlConnection(BStr);//SqlBulkCopy裡面就只能放SqlConnection,不能放別的像是OleDbConnection

                SqlBulkCopy SBC = new SqlBulkCopy(Bulkcn);

                //複製到目的地的哪個資料表
                SBC.DestinationTableName = "SeaData";

                //設定你要複製過去的DataTable的每個欄位要對應到目的地的哪個欄位
                //SBC.ColumnMappings.Add("DataTable的欄位A", "資料庫裡的資料表的的欄位A");
                SBC.ColumnMappings.Add("DateX", "DateX");
                SBC.ColumnMappings.Add("dat", "dat");
                SBC.ColumnMappings.Add("lonX", "lonX");
                SBC.ColumnMappings.Add("chll", "chll");
                SBC.ColumnMappings.Add("sa", "sa");
                SBC.ColumnMappings.Add("cerrentX", "cerrentX");
                SBC.ColumnMappings.Add("cerrentY", "cerrentY");
                SBC.ColumnMappings.Add("waveh", "waveh");
                SBC.ColumnMappings.Add("tide", "tide");
                SBC.ColumnMappings.Add("uv", "uv");

                Bulkcn.Open();

                //假設DT1是已經有資料的DataTable,直接放進去就可以開始寫入了
                SBC.WriteToServer(dt);
                SBC.Close();
                Bulkcn.Close();
            }
            catch (Exception ex)
            {
                return("資料上傳異常1" + ex.Message);
            }



            ////從暫存table轉資料到正式資料表,會過濾重覆的資料
            //CodeDao dao = new CodeDao();
            //string transresult = dao.transData();
            //if (!transresult.Equals("OK"))
            //{
            //    return "資料上傳異常2";
            //}


            ////刪除匯入的資料
            //dao.clearnTmpData();



            return("上傳完成");
        }
 public DocumentTypeIconFileResolver(HttpServerUtilityBase server, UmbracoSettings settings, UrlHelper url)
     : base(new DirectoryInfo(server.MapPath(settings.UmbracoFolders.DocTypeIconFolder)), url)
 {
 }
Exemplo n.º 28
0
        public static string OpacityImages(HttpServerUtilityBase Server, string backImagePath, List <string> ListfrontImagePath, string facebookId)
        {
            string pathRoute = SiteSettings.MergeImageRoute;
            Image  backImage = null;
            int    merge     = 235;

            using (Stream backImageStream = HttpWebRequest.Create(backImagePath).GetResponse().GetResponseStream())
            {
                try
                {
                    backImage = Image.FromStream(backImageStream);
                }
                catch
                {
                }
                using (var bitmap = new Bitmap(backImage.Width, backImage.Height))
                {
                    using (var canvas = Graphics.FromImage(bitmap))
                    {
                        int maxWidth = 16;


                        canvas.InterpolationMode = InterpolationMode.HighQualityBilinear;
                        canvas.DrawImage(backImage, new Rectangle(0, 0, backImage.Width, backImage.Height), new Rectangle(0, 0, backImage.Width, backImage.Height), GraphicsUnit.Pixel);
                        int    y              = backImage.Height - maxWidth;
                        int    x              = merge;
                        int    index          = 0;
                        Image  frontImage     = null;
                        string frontImagePath = string.Empty;
                        float  opacity        = 1;
                        while (y >= 0)
                        {
                            if (index < ListfrontImagePath.Count)
                            {
                                opacity        = (float)0.2;
                                frontImagePath = ListfrontImagePath[index];
                                index++;
                            }
                            else
                            {
                                opacity        = (float)0.7;
                                frontImagePath = "/Asset/uploads/avatar/Black.jpg";
                            }

                            try
                            {
                                ColorMatrix cmxPic = new ColorMatrix();
                                cmxPic.Matrix33 = opacity;

                                ImageAttributes iaPic = new ImageAttributes();
                                iaPic.SetColorMatrix(cmxPic, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);


                                if (!frontImagePath.Contains("http"))
                                {
                                    frontImage = Image.FromFile(Server.MapPath(".." + frontImagePath));
                                }
                                else
                                {
                                    Stream frontImageStream = HttpWebRequest.Create(frontImagePath).GetResponse().GetResponseStream();
                                    frontImage = Image.FromStream(frontImageStream);
                                }
                                if (frontImage.Width != maxWidth)
                                {
                                    double aspectRatio = (double)frontImage.Width / (double)frontImage.Height;
                                    int    newWidth    = maxWidth;
                                    int    newHeight   = (int)Math.Round(newWidth / aspectRatio);
                                    frontImage = new Bitmap(frontImage, newWidth, newHeight);
                                }
                                canvas.DrawImage(frontImage, new Rectangle(x, y, frontImage.Width, frontImage.Height), 0, 0, frontImage.Width, frontImage.Height, GraphicsUnit.Pixel, iaPic);

                                if (x >= backImage.Width - merge)
                                {
                                    merge = merge - maxWidth;
                                    y     = y - frontImage.Height;
                                    x     = merge;
                                }
                                else
                                {
                                    x = x + frontImage.Width;
                                }
                                frontImage.Dispose();
                            }
                            catch
                            {
                            }
                        }

                        //foreach (string frontImagePath in ListfrontImagePath)
                        //{

                        //    Image frontImage = null;
                        //    try
                        //    {
                        //        if (!frontImagePath.Contains("http"))
                        //        {
                        //            frontImage = Image.FromFile(Server.MapPath(frontImagePath));
                        //        }
                        //        else
                        //        {
                        //            Stream frontImageStream = HttpWebRequest.Create(frontImagePath).GetResponse().GetResponseStream();
                        //            frontImage = Image.FromStream(frontImageStream);
                        //        }
                        //        if (frontImage.Width != maxWidth)
                        //        {

                        //            double aspectRatio = (double)frontImage.Width / (double)frontImage.Height;
                        //            int newWidth = maxWidth;
                        //            int newHeight = (int)Math.Round(newWidth / aspectRatio);
                        //            frontImage = new Bitmap(frontImage, newWidth, newHeight);
                        //        }
                        //        canvas.DrawImage(frontImage, new Rectangle(x, y, frontImage.Width, frontImage.Height), 0, 0, frontImage.Width, frontImage.Height, GraphicsUnit.Pixel, iaPic);

                        //        if (x >= backImage.Width - merge)
                        //        {
                        //            y = y - frontImage.Height;
                        //            x = merge;
                        //        }
                        //        else
                        //        {

                        //            x = x + frontImage.Width;
                        //        }
                        //        frontImage.Dispose();
                        //    }
                        //    catch
                        //    {

                        //    }
                        //}
                        canvas.Save();
                    }
                    string fileName = facebookId + ".png";
                    bitmap.Save(Server.MapPath(pathRoute) + fileName, ImageFormat.Png);
                    backImage.Dispose();
                    bitmap.Dispose();
                    return(pathRoute + fileName);
                }
            }
        }
Exemplo n.º 29
0
        public ModelManager(HttpServerUtilityBase server)
        {
            string xmlFilePath = server.MapPath("/Data/LoadModelDecision.xml");

            xmlDoc.Load(xmlFilePath);
        }
Exemplo n.º 30
0
        /// <summary>
        /// TSVファイルから読み込み
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="hasHeader"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static List <T> Read <T>(string fileName, bool hasHeader, Encoding encoding = null)
        {
            // if null encode
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            //Tタイプのプロパティ取得
            Type          type   = typeof(T);
            List <string> header = (from p in (type.GetProperties())
                                    select p.Name).ToList <string>();

            //TSVから読み込み結果リスト
            List <T>     resultList = new List <T>();
            StreamReader fileStream = null;

            try
            {
                string filePath;
                try
                {
                    filePath = HttpContext.Current.Server.MapPath(fileName);
                }
                catch (Exception e)
                {
                    try
                    {
                        LocalDataStoreSlot    serverData = Thread.GetNamedDataSlot("Server");
                        HttpServerUtilityBase server     = Thread.GetData(serverData) as HttpServerUtilityBase;
                        filePath = server.MapPath(fileName);
                    }
                    catch (Exception)
                    {
                        throw e;
                    }
                }
                fileStream = new StreamReader(filePath, encoding);
                ConstructorInfo ci = type.GetConstructor(new Type[0]);
                string          line;
                // TSVファイルにヘッダがある場合
                if (hasHeader)
                {
                    fileStream.ReadLine();
                }
                while (!fileStream.EndOfStream)
                {
                    line = fileStream.ReadLine();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }
                    string[] lineArr = line.Split('\t');
                    //結果対象構造
                    T detail = (T)ci.Invoke(new Object[0]);
                    //TSVからdetailに読み込む
                    for (int i = 0; i < lineArr.Length; i++)
                    {
                        (type.GetProperty(header[i])).SetValue(detail, lineArr[i].Trim(), null);
                    }
                    resultList.Add(detail);
                }
            }
            catch (FileNotFoundException fex)
            {
                _logger.Info(fex.Message);
            }
            catch (Exception ex)
            {
                resultList.Clear();
                StringBuilder errLogMsg = new StringBuilder();
                errLogMsg.Append("\r\n");
                errLogMsg.Append("0: TSVファイル(" + fileName + ")から取得するエラー: ---Exception.\r\n");
                errLogMsg.Append("0: ExceptionType: " + ex.GetType() + "\r\n");
                errLogMsg.Append("0: ExceptionMessage: " + ex.Source.ToString(CultureInfo.InvariantCulture) + "\r\n");
                errLogMsg.Append("0: ExceptionStackTrace: " + ex.StackTrace + "\r\n");
                errLogMsg.Append("0: ExceptionMessage: " + ex.Message + "\r\n");
                errLogMsg.Append("0: ExceptionTargetSite: " + ex.TargetSite + "\r\n");
                _logger.Fatal(errLogMsg.ToString());
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
            return(resultList);
        }