MapPath() public method

public MapPath ( string path ) : string
path string
return string
        public static void AddErrorLog(string strSql, string exStr)
        {
            try
            {
                StreamWriter sw;
                DateTime     Date = DateTime.Now;
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("../log/")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("../log/"));
                }
                System.Web.HttpServerUtility Server = System.Web.HttpContext.Current.Server;
                string   fileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";
                FileInfo fi       = new FileInfo(Server.MapPath("../log" + "/" + fileName));

                if (fi.Exists)
                {
                    sw = File.AppendText(Server.MapPath("../log" + "/" + fileName));
                }
                else
                {
                    File.Create(Server.MapPath("../log") + "/" + fileName).Close();
                    sw = File.AppendText(Server.MapPath("../log" + "/" + fileName));
                }
                sw.WriteLine("*----------------------------------------------------------");
                sw.WriteLine("err_Time:" + Date.ToString("yyyy-MM-dd HH:mm:ss") + "");
                sw.WriteLine("err_SqlStr:" + strSql + "");
                sw.WriteLine("err_ExStr:" + exStr);
                sw.WriteLine("----------------------------------------------------------*");
                sw.Flush();
                sw.Close();
            }
            finally
            {
            }
        }
Example #2
0
        public static string Save(HttpServerUtility server, Stream stream, string fileName) {

            string fileExtension = Path.GetExtension(fileName);
            string relativePath = $"{RootFileName}/{Unknow}/";
            string savePath = server.MapPath($"~/{relativePath}");

            if (!string.IsNullOrEmpty(fileExtension)) {
                //去掉extension的.
                relativePath = $"{RootFileName}/{fileExtension.Substring(1)}/";
                savePath = server.MapPath($"~/{relativePath}/");
            }

            if (!Directory.Exists(savePath)) {
                Directory.CreateDirectory(savePath);
            }

            string newFileName = Guid.NewGuid().ToString("N") + fileExtension;
            string saveFile = Path.Combine(savePath, newFileName);
            bool success = FileHelper.WriteFile(stream, saveFile);
            string retFile = "";
            if (success) {
                retFile = $"{Address}{relativePath}{newFileName}";
            }

            return retFile;
        }
Example #3
0
    //考生提交实践题答案
    public int StuPutPracAns(string sId, string examId, string path)
    {
        try
        {
            StuPaper stuPaper = db.StuPaper.First(t => t.StudentId == sId && t.ExamId == decimal.Parse(examId));
            if (stuPaper.stuAnsPath != null)
            {
                System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
                string phth = server.MapPath(@stuPaper.stuAnsPath);

                if (File.Exists(server.MapPath(@stuPaper.stuAnsPath)))
                {
                    File.Delete(server.MapPath(stuPaper.stuAnsPath));
                }
            }

            stuPaper.stuAnsPath = path;
            db.SubmitChanges();

            return(1);
        }
        catch
        {
            return(-1);
        }
    }
Example #4
0
        const string Token = "youotech"; //定义一个局部变量不可以被修改,这里定义的变量要与接口配置信息中填写的Token一致

        #endregion Fields

        #region Methods

        /// <summary>
        /// 写日志(用于跟踪),可以将想打印出的内容计入一个文本文件里面,便于测试
        /// </summary>
        public static void WriteLog(string strMemo, HttpServerUtility server)
        {
            string filename = server.MapPath("/log/log.txt");//在网站项目中建立一个文件夹命名logs(然后在文件夹中随便建立一个web页面文件,避免网站在发布到服务器之后看不到预定文件)
            if (!Directory.Exists(server.MapPath("//log//")))
                Directory.CreateDirectory("//log//");
            StreamWriter sr = null;
            try
            {
                if (!File.Exists(filename))
                {
                    sr = File.CreateText(filename);
                }
                else
                {
                    sr = File.AppendText(filename);
                }
                sr.WriteLine(strMemo);
            }
            catch
            {
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }
        }
Example #5
0
        public static void Init(HttpServerUtility server)
        {
            string configPath = Path.Combine(PARENT_CONFIG_PATH, DefaultConfigName);
            DefaultConfigPath = server.MapPath(configPath);

            //By default if there's no config let's create a sqlite db.
            string defaultConfigPath = DefaultConfigPath;

            string sqlitePath = Path.Combine(DATA_FOLDER, DEFAULT_SQLITE_NAME);
            sqlitePath = server.MapPath(sqlitePath);

            if (!File.Exists(defaultConfigPath))
            {
                ConfigFile file = new ConfigFile(defaultConfigPath);

                file.Set(DbConstants.KEY_DB_TYPE, DbConstants.DB_TYPE_SQLITE);
                file.Set(DbConstants.KEY_FILE_NAME, sqlitePath);
                file.Save();

                CurrentConfigFile = file;
            }
            else
            {
                CurrentConfigFile = new ConfigFile(defaultConfigPath);
                CurrentConfigFile.Load();
            }

            CurrentDbProvider = DbProviderFactory.Create(CurrentConfigFile);
        }
Example #6
0
    /// <summary>
    /// 生成PDF格式的采购合同
    /// </summary>
    /// <param name="savePath"></param>
    /// <param name="strHTML"></param>
    public void CreatePDFContract(string fileName, string strHTML)
    {
        string savePath = Server.MapPath("/Download/" + fileName + ".pdf");

        Document  document = new Document(PageSize.A4);
        PdfWriter writer   = PdfWriter.GetInstance(document, new FileStream(savePath, FileMode.Create));

        document.Open();

        try
        {
            FontFactory.RegisterFamily("宋体 常规", "simsun", @"c:\windows\fonts\simsun.ttc,0");

            HTMLWorker htmlWorker = new HTMLWorker(document);
            htmlWorker.Parse(new StringReader(strHTML));
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            document.Close();
        }
    }
Example #7
0
 public static void Register(HttpServerUtility server)
 {
     ConstantManager.LogPath = server.MapPath("~/Areas/Admin/LogFiles/");
     ConstantManager.ConfigPath = server.MapPath("~/Areas/Admin/AdminConfig.xml");
     ConstantManager.SavedPath = server.MapPath("~/Areas/Admin/SavedPages");
     ConstantManager.TrainingFilePath = server.MapPath("~/UploadedExcelFiles/ProductName.txt");
     ConstantManager.DistanceFilePath = server.MapPath("~/CalculateMarketDistance.xml");
     ConstantManager.IsParserRunning = false;
 }
Example #8
0
        public static string DownloadImage(string url,string mid, HttpServerUtility obj)
        {
            byte[] data;
            string path="";
            using (WebClient client = new WebClient())
            {
                data = client.DownloadData(url);
            }
            if (data == null)
                return null;
            path = "Images/"+mid+"_"+ url.GetHashCode() + ".jpg";
                if (!File.Exists(obj.MapPath(path)))
                    File.WriteAllBytes(obj.MapPath(path), data);

            return path;
        }
Example #9
0
        /// <summary>
        /// Creates a template file if it does not already exists, and uses a default text to insert. Returns the new path
        /// </summary>
        public string CreateTemplateFileIfNotExists(string name, string type, string location, HttpServerUtility server, string contents = "")
        {
            if (type == RazorC)
            {
                if (!name.StartsWith("_"))
                    name = "_" + name;
                if (Path.GetExtension(name) != ".cshtml")
                    name += ".cshtml";
            }
            else if (type == RazorVb)
            {
                if (!name.StartsWith("_"))
                    name = "_" + name;
                if (Path.GetExtension(name) != ".vbhtml")
                    name += ".vbhtml";
            }
            else if (type == TokenReplace)
            {
                if (Path.GetExtension(name) != ".html")
                    name += ".html";
            }

            var templatePath = Regex.Replace(name, @"[?:\/*""<>|]", "");
            var absolutePath = server.MapPath(Path.Combine(GetTemplatePathRoot(location, App), templatePath));

            if (!File.Exists(absolutePath))
            {
                var stream = new StreamWriter(File.Create(absolutePath));
                stream.Write(contents);
                stream.Flush();
                stream.Close();
            }

            return templatePath;
        }
Example #10
0
        public void GetCertificate(HttpContext context)
        {
            string    employeeID = context.Request.QueryString["empID"];
            Cerficate cerficate  = new CerficateBLL().GetModelList(" employeeID = '" + employeeID + "' AND isMain = 1 ").FirstOrDefault();

            if (cerficate != null)
            {
                System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
                string filePath          = server.MapPath(string.Format("~/{0}/{1}", Convert.ToString(ConfigurationManager.AppSettings["fileSavePath"]), cerficate.FILEPATH));
                System.Drawing.Image img = new Bitmap(filePath, true);
                //aFile.Close();
                System.Drawing.Image img2 = new ImageHelper().GetHvtThumbnail(img, 400, 0);


                //将Image转换成流数据,并保存为byte[]

                MemoryStream mstream = new MemoryStream();
                img2.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] byData = new Byte[mstream.Length];
                mstream.Position = 0;
                mstream.Read(byData, 0, byData.Length); mstream.Close();
                if (byData.Length > 0)
                {
                    MemoryStream ms = new MemoryStream(byData);
                    context.Response.Clear();
                    context.Response.ContentType = "image/jpg";
                    context.Response.OutputStream.Write(byData, 0, byData.Length);
                    context.Response.End();
                }
            }
        }
Example #11
0
        private void PrepareData()
        {
            MapInfo.Data.Table mdbTable   = MapInfo.Engine.Session.Current.Catalog[SampleConstants.EWorldAlias];
            MapInfo.Data.Table worldTable = MapInfo.Engine.Session.Current.Catalog[SampleConstants.ThemeTableAlias];
            // worldTable is loaded by preloaded mapinfo workspace file specified in web.config.
            // and MS Access table in this sample is loaded manually.
            // we are not going to re-load it again once it got loaded because its content is not going to change in this sample.
            // we will get performance gain if we use Pooled MapInfo Session.
            // Note: It's better to put this MS Access table into pre-loaded workspace file,
            //       so we don't need to do below code.
            //       We manually load this MS Access in this sample for demonstration purpose.
            if (mdbTable == null)
            {
                System.Web.HttpServerUtility util = HttpContext.Current.Server;
                string dataPath = util.MapPath("");
                mdbTable = MapInfo.Engine.Session.Current.Catalog.OpenTable(System.IO.Path.Combine(dataPath, SampleConstants.EWorldTabFileName));

                string[] colAlias = SampleConstants.BoundDataColumns;
                // DateBinding columns
                Column col0 = MapInfo.Data.ColumnFactory.CreateDoubleColumn(colAlias[0]);
                col0.ColumnExpression = mdbTable.Alias + "." + colAlias[0];
                Column col1 = MapInfo.Data.ColumnFactory.CreateIntColumn(colAlias[1]);
                col1.ColumnExpression = mdbTable.Alias + "." + colAlias[1];
                Column col2 = MapInfo.Data.ColumnFactory.CreateIntColumn(colAlias[2]);
                col2.ColumnExpression = mdbTable.Alias + "." + colAlias[2];

                Columns cols = new Columns();
                cols.Add(col0);
                cols.Add(col1);
                cols.Add(col2);

                // Databind MS Access table data to existing worldTable.
                worldTable.AddColumns(cols, BindType.DynamicCopy, mdbTable, SampleConstants.SouceMatchColumn, Operator.Equal, SampleConstants.TableMatchColumn);
            }
        }
Example #12
0
        public ResponseResult PostSentence(dynamic sentenceObj)
        {
            try
            {
                string _sentence = Convert.ToString(sentenceObj.sentence);
                if (string.IsNullOrEmpty(_sentence))
                {
                    return(new ResponseResult {
                        Code = 4002, Message = "内容不能为空!"
                    });
                }

                System.Web.HttpServerUtility Server = System.Web.HttpContext.Current.Server;
                string all_path = Server.MapPath("~/Upload");
                if (Directory.Exists(all_path))
                {
                    WriteTxt(all_path + "/Sentence.txt", _sentence, true);
                }
                else
                {
                    Directory.CreateDirectory(all_path);
                    WriteTxt(all_path + "/Sentence.txt", _sentence, true);
                }
                return(new ResponseResult {
                    Code = 2000, Message = "操作成功!"
                });
            }
            catch (Exception ex)
            {
                return(new ResponseResult {
                    Code = 4004, Message = ex.Message
                });
            }
        }
Example #13
0
        /// <summary>
        /// First converts tildeDirectoryPath to lowercase.
        /// 
        /// Then uses the server to convert tildeDirectoryPath
        /// to an absolute base directory path.
        /// 
        /// Then produces the list of absolute directory paths
        /// whose tree roots itself at this base path.
        /// 
        /// If there is an error then may return an empty list.
        /// </summary>
        public static List<string> AbsoluteDirectoryPathList(HttpServerUtility server, string tildeDirectoryPath)
        {
            List<string> list = new List<string>();

            string path = tildeDirectoryPath.ToLower();

            if (StringTools.IsTrivial(path))
                goto returnstatement;

            if (path[0] != '~')
                goto returnstatement;

            int n = path.Length;

            if (path[n - 1] != '/')
                path = path + '/';

            if (!SourceTools.OKtoServe(path, true))
                goto returnstatement;

            try
            {
                string directoryPath = server.MapPath(path);
                AbsoluteDirectoryPathListHelper(list, directoryPath);
            }
            catch { }

            returnstatement:

            return list;
        }
Example #14
0
    public static void Start(HttpServerUtility server)
    {
      DeNSo.Configuration.BasePath = server.MapPath("~/App_Data");
      DeNSo.Configuration.EnableJournaling = true;

      Session.DefaultDataBase = "densodb_webapp";
      Session.Start();
    }
Example #15
0
        internal static void LoadDiskCache(HttpServerUtility server)
        {
            var cache = server.MapPath("~/App_Data/api_start2.json");
            if(!File.Exists(cache)) return;

            start2Content = File.ReadAllText(cache);
            start2Timestamp = (long)((File.GetLastWriteTimeUtc(cache) - Utils.UnixTimestamp.Epoch.UtcDateTime).TotalMilliseconds);
        }
Example #16
0
        public void ProcessRequest(HttpContext context)
        {
            System.Web.HttpRequest       Request  = context.Request;
            System.Web.HttpServerUtility Server   = context.Server;
            System.Web.HttpResponse      Response = context.Response;

            _file = Request.QueryString["file"];

            try
            {
                Type = (DownloadType)Enum.Parse(typeof(DownloadType), Request.QueryString["Type"]);
            }
            catch (Exception Ex)
            {
                Response.Redirect("~/");
            }


            string path = "";

            switch (_Type)
            {
            case DownloadType.News:
                path  = Folders.NewsFile + "/";
                _file = string.Format("{0}/{1}{2}", WebContext.StartDir, path, _file);
                break;

            case DownloadType.Downloads:
                //_file = Server.MapPath(_file);
                break;

            default:
                _file = string.Format("{0}/{1}{2}", WebContext.StartDir, path, _file);
                break;
            }



            FileInfo fi = new FileInfo(Server.MapPath(_file));

            string mimeType = IO.GetMimeType(_file);

            if (mimeType == "")
            {
                mimeType = "application/force-download";
            }

            //Response.AddHeader("Content-Transfer-Encoding", "binary");


            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fi.Name);
            Response.AddHeader("Content-Type", mimeType);
            Response.AddHeader("Content-Length", fi.Length.ToString());
            Response.WriteFile(fi.FullName);
            Response.Flush();
            Response.End();
        }
Example #17
0
        public static DataSet getDataSetFromExcel(FileUpload FileUpload1, HttpServerUtility Server)
        {
            if (FileUpload1.HasFile)
            {
                string fileName = Path.GetFileName(FileUpload1.FileName);
                string filePath = Server.MapPath("~/Excel/" + fileName);
                string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);

                try
                {

                    MemoryStream stream = new MemoryStream(FileUpload1.FileBytes);
                    IExcelDataReader excelReader;

                    if (fileExtension == ".xls")
                    {
                        excelReader = ExcelReaderFactory.CreateBinaryReader(stream);

                        excelReader.IsFirstRowAsColumnNames = true;
                        DataSet result = excelReader.AsDataSet();

                        DataTable myTable = result.Tables[0];

                        excelReader.Close();
                        return result;
                    }
                    else if (fileExtension == ".xlsx")
                    {
                        excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

                        //excelReader.IsFirstRowAsColumnNames = true;
                        DataSet result = excelReader.AsDataSet();

                        DataTable myTable = result.Tables[0];

                        excelReader.Close();
                        return result;
                    }
                    else if (fileExtension == ".csv")
                    {
                        //Someone else can implement this
                        return null;
                    }
                    else
                    {
                        throw new Exception("Unhandled Filetype");
                    }
                }
                catch
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
Example #18
0
        public static void Init(HttpServerUtility server)
        {
            lock (_lock)
            {
                if (Debugger.IsAttached)
                    BasicConfigurator.Configure();
                else
                    XmlConfigurator.Configure();

                string configPath = Path.Combine(PARENT_CONFIG_PATH, DefaultConfigName);
                DefaultConfigPath = server.MapPath(configPath);

                RootDir = server.MapPath(".");

                log.Debug("DYLD_FALLBACK_LIBRARY_PATH: " + Environment.GetEnvironmentVariable("DYLD_FALLBACK_LIBRARY_PATH"));
                log.Debug("PWD: " + Environment.CurrentDirectory);

                //By default if there's no config let's create a sqlite db.
                string defaultConfigPath = DefaultConfigPath;

                string sqlitePath = Path.Combine(DATA_FOLDER, DEFAULT_SQLITE_NAME);
                sqlitePath = server.MapPath(sqlitePath);

                if (!File.Exists(defaultConfigPath))
                {
                    ConfigFile file = new ConfigFile(defaultConfigPath);

                    file.Set(DbConstants.KEY_DB_TYPE, DbConstants.DB_TYPE_SQLITE);
                    file.Set(DbConstants.KEY_FILE_NAME, sqlitePath);
                    file.Save();

                    CurrentConfigFile = file;
                }
                else
                {
                    CurrentConfigFile = new ConfigFile(defaultConfigPath);
                    CurrentConfigFile.Load();
                }

                CurrentDbProvider = DbProviderFactory.Create(CurrentConfigFile);
                _inited = true;
            }

        }
 public Tuple<string, string> GetBannerPath(string programId, HttpServerUtility Server)
 {
     var banner = DefaultBanner;
     var banner2x = DefaultBanner2x;
     if (!string.IsNullOrEmpty(programId))
     {
         var programBanner = string.Format("~/images/Banners/{0}.png",
                                           programId);
         var programBanner2x = string.Format("~/images/Banners/{0}@2x.png",
                                             programId);
         if (File.Exists(Server.MapPath(programBanner)))
         {
             banner = programBanner;
             if (File.Exists(Server.MapPath(programBanner2x)))
             {
                 banner2x = programBanner2x;
             }
             else
             {
                 banner2x = null;
             }
         }
         else
         {
             programBanner = string.Format("~/images/Banners/{0}.jpg",
                                           programId);
             programBanner2x = string.Format("~/images/Banners/{0}@2x.jpg",
                                             programId);
             if (File.Exists(Server.MapPath(programBanner)))
             {
                 banner = programBanner;
                 if (File.Exists(Server.MapPath(programBanner2x)))
                 {
                     banner2x = programBanner2x;
                 }
                 else
                 {
                     banner2x = null;
                 }
             }
         }
     }
     return new Tuple<string, string>(banner, banner2x);
 }
        public static string CheckFileUpLoadDirectory(string applicationPath, System.Web.HttpServerUtility server, UploadFileType type = UploadFileType.File)
        {
            string dic = server.MapPath(applicationPath + "/UploadFile/" + GetFileUpLoadPath(type));

            if (!Directory.Exists(dic))
            {
                Directory.CreateDirectory(dic);
            }
            return(dic);
        }
Example #21
0
		public void PopulateSampleFiles(HttpServerUtility server, string wildcard, DropDownList ddl)
		{
			string sampleDir = server.MapPath("SampleFiles");
			ddl.Items.Add(new ListItem("Choose sample", ""));
			DirectoryInfo di = new DirectoryInfo(sampleDir);
			foreach (FileInfo f in di.GetFiles(wildcard))
			{
				ddl.Items.Add(new ListItem(Path.GetFileNameWithoutExtension(f.Name), f.Name));
			}
		}
Example #22
0
        private void InitState()
        {
            MapInfo.Mapping.Map myMap = this.GetMapObj();

            // We need to put original state of applicatin into HttpApplicationState.
            if (Application.Get("DataAccessWeb") == null)
            {
                System.Collections.IEnumerator iEnum = MapInfo.Engine.Session.Current.MapFactory.GetEnumerator();
                // Put maps into byte[] objects and keep them in HttpApplicationState
                while (iEnum.MoveNext())
                {
                    MapInfo.Mapping.Map tempMap = iEnum.Current as MapInfo.Mapping.Map;
                    byte[] mapBits = MapInfo.WebControls.ManualSerializer.BinaryStreamFromObject(tempMap);
                    Application.Add(tempMap.Alias, mapBits);
                }

                // Load Named connections into catalog.
                if (MapInfo.Engine.Session.Current.Catalog.NamedConnections.Count == 0)
                {
                    System.Web.HttpServerUtility util = HttpContext.Current.Server;
                    string path     = util.MapPath(string.Format(""));
                    string fileName = System.IO.Path.Combine(path, "namedconnection.xml");
                    MapInfo.Engine.Session.Current.Catalog.NamedConnections.Load(fileName);
                }

                // Put Catalog into a byte[] and keep it in HttpApplicationState
                byte[] catalogBits = MapInfo.WebControls.ManualSerializer.BinaryStreamFromObject(MapInfo.Engine.Session.Current.Catalog);
                Application.Add("Catalog", catalogBits);

                // Put a marker key/value.
                Application.Add("DataAccessWeb", "Here");
            }
            else
            {
                // Apply original Catalog state.
                Object obj = Application.Get("Catalog");
                if (obj != null)
                {
                    Object tempObj = MapInfo.WebControls.ManualSerializer.ObjectFromBinaryStream(obj as byte[]);
                }

                // Apply original Map object state.
                obj = Application.Get(MapControl1.MapAlias);
                if (obj != null)
                {
                    Object tempObj = MapInfo.WebControls.ManualSerializer.ObjectFromBinaryStream(obj as byte[]);
                }
            }

            // Set the initial zoom, center and size of the map
            // This step is needed because you may get a dirty map from mapinfo Session.Current which is retrived from session pool.
            myMap.Zoom   = new MapInfo.Geometry.Distance(25000, DistanceUnit.Mile);
            myMap.Center = new DPoint(27775.805792979896, -147481.33999999985);
            myMap.Size   = new System.Drawing.Size((int)this.MapControl1.Width.Value, (int)this.MapControl1.Height.Value);
        }
Example #23
0
        public static Bootstrapper RegisterStandard(this Bootstrapper bootstrapper, HttpServerUtility server)
        {
            FileSystemStorage.StoragePath = server.MapPath("~/Storage");
            FormsCore.Instance.BaseUrl = "http://localhost:36258";

            bootstrapper.UnityContainer
                .RegisterType<IFileStorage, FileSystemStorage>()
                .RegisterType<ILogger, TraceLogger>();

            return bootstrapper;
        }
        public static void Initialize(HttpServerUtility server)
        {
            FileName = server.MapPath ("~/App_Data/Structure.json");

            _contentManager.Synchronize("Bifrost");

            if (_structure == null)
                Load ();

            if (_structure == null)
                Generate ();
        }
Example #25
0
 // todo: try to cache the result of settings-stored in a static variable, this full check
 // todo: shouldn't have to happen every time
 /// <summary>
 /// Returns true if the Portal HomeDirectory Contains the 2sxc Folder and this folder contains the web.config and a Content folder
 /// </summary>
 public void EnsurePortalIsConfigured(SxcInstance sxc, HttpServerUtility server, string controlPath)
 {
     var sexyFolder = new DirectoryInfo(server.MapPath(Path.Combine(sxc.AppPortalSettings.HomeDirectory, Settings.TemplateFolder)));
     var contentFolder = new DirectoryInfo(Path.Combine(sexyFolder.FullName, Constants.ContentAppName));
     var webConfigTemplate = new FileInfo(Path.Combine(sexyFolder.FullName, Settings.WebConfigFileName));
     if (!(sexyFolder.Exists && webConfigTemplate.Exists && contentFolder.Exists))
     {
         // configure it
         var tm = new TemplateManager(sxc.App);
         tm.EnsureTemplateFolderExists(Settings.TemplateLocations.PortalFileSystem);
     };
 }
        public static string[] GetConnectionExcel(HttpPostedFile HttpFileUpload,HttpServerUtility ServerHU)
        {
            string[] strExcelConn = new string[2];
             string strFileName = ServerHU.HtmlEncode(HttpFileUpload.FileName);
             string strExtension = Path.GetExtension(strFileName);

             if (strExtension != ".xls" && strExtension != ".xlsx")
             {
            return strExcelConn;
             }

             string strUploadFileName = "~/UploadFiles/" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
             strExcelConn[1] = strUploadFileName;
             HttpFileUpload.SaveAs(ServerHU.MapPath(strUploadFileName));

             //if (strExtension == ".xls")
             //   strExcelConn[0] = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ServerHU.MapPath(strUploadFileName) + ";Extended Properties='Excel 8.0;HDR=YES;'";
             //else
            strExcelConn[0] = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ServerHU.MapPath(strUploadFileName) + ";Extended Properties='Excel 12.0 Xml;HDR=YES;'";

             return strExcelConn;
        }
Example #27
0
        public static void DeletePicture(NietoYostenDbDataContext db, HttpServerUtility server, int pictureId)
        {
            var picture = db.Pictures.SingleOrDefault(p => p.Id == pictureId);
            string folderName = picture.Album.FolderName;
            string fileName = picture.FileName;

            // Delete pictures from file system
            string originalPicFile = server.MapPath(string.Format(
                       "~/pictures/original/{0}/{1}", folderName, fileName));
            System.IO.File.Delete(originalPicFile);

            string webPicFile = server.MapPath(string.Format(
                "~/pictures/web/{0}/{1}", folderName, fileName));
            System.IO.File.Delete(webPicFile);

            string thumbPicFile = server.MapPath(string.Format(
                "~/pictures/thumb/{0}/{1}", folderName, fileName));
            System.IO.File.Delete(thumbPicFile);

            // Delete picture from DB
            db.Pictures.DeleteOnSubmit(picture);
        }
Example #28
0
 public static string Save(HttpServerUtility server, HttpPostedFile postedFile, string folder, string name = null)
 {
     if (postedFile == null) throw new ArgumentNullException("postedFile");
     if (folder == null) throw new ArgumentNullException("folder");
     if (name == null)
     {
         name = Path.GetRandomFileName();
         name = Path.ChangeExtension(name, "xlsx");
     }
     var fullPath = Path.Combine(server.MapPath(folder), name);
     postedFile.SaveAs(fullPath);
     return fullPath;
 }
Example #29
0
        public void InitLogger(HttpServerUtility server)
        {
            // create the file logger
            Logger fileLogger = new FileLogger(
                server.MapPath(@"~\Logs\logfile.log"));

#if DEBUG
            fileLogger.SeverityThreshold = LogSeverity.Info;
#else
            fileLogger.SeverityThreshold = LogSeverity.Status;     
#endif

            Logger.AddLogger("File", fileLogger);
        }
        public static void Initialize(HttpServerUtility server)
        {
            lock (_lock)
            {
                if (null != PMixinsRecipesZipFilePath)
                    return;

                if (null == server)
                    throw new ArgumentNullException("server");

                PMixinsRecipesZipFilePath = server.MapPath(
                    @"/Content/pMixins.Mvc.Recipes.zip");
            }
        }
Example #31
0
		public string FetchSample(HttpServerUtility server, string file)
		{
			StringWriter sw = new StringWriter();
			string filename = server.MapPath(Path.Combine("SampleFiles", file));
			using (StreamReader rdr = new StreamReader(filename))
			{
				string line = rdr.ReadLine();
				while (line != null)
				{
					sw.WriteLine(line);
					line = rdr.ReadLine();
				}
			}
			return sw.ToString();
		}
Example #32
0
    /// <summary>
    /// 获取配置文件
    /// </summary>
    /// <param name="server"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    public static string GetSiteSetting(System.Web.HttpServerUtility server, string name)
    {
        ConfigXmlDocument cfxd = new ConfigXmlDocument();

        cfxd.Load(server.MapPath(SiteConfigPath));
        try
        {
            string value = cfxd.GetElementsByTagName(name)[0].InnerText;
            return(value);
        }
        catch
        {
            return("");
        }
    }
        public static void OutputExcel(System.Web.HttpServerUtility server, System.Web.HttpResponse response, string filename)
        {
            string path = server.MapPath(filename + ".xls");

            FileInfo file = new FileInfo(path);

            response.Clear();
            response.Charset         = "GB2312";
            response.ContentEncoding = Encoding.UTF8;
            response.AddHeader("Content-Disposition", "attachment; filename=" + server.UrlEncode(file.Name));
            response.AddHeader("Content-Length", file.Length.ToString());
            response.ContentType = "application/ms-excel";
            response.WriteFile(file.FullName);
            response.End();
        }
Example #34
0
        //优惠券明细
        private void GetCouponDetail(Dictionary <string, object> dicPar)
        {
            ///要检测的参数信息
            List <string> pra = new List <string>()
            {
                "GUID", "USER_ID", "couponcode"
            };

            //检测方法需要的参数
            if (!CheckActionParameters(dicPar, pra))
            {
                return;
            }

            string GUID       = dicPar["GUID"].ToString();
            string USER_ID    = dicPar["USER_ID"].ToString();
            string couponcode = dicPar["couponcode"].ToString();

            dt = bll.GetCouponDetail(couponcode);
            if (dt != null && dt.Rows.Count > 0)
            {
                dt.Columns.Add("couponimg", typeof(string));
                string path = string.Empty;
                if (!File.Exists(server.MapPath("~/erqimg/" + couponcode + ".jpg")))
                {
                    path = DoWaitProcess(couponcode);
                }
                else
                {
                    path = "/erqimg/" + couponcode + ".jpg";
                }
                dt.Rows[0]["couponimg"] = Helper.GetAppSettings("imgUrl") + path;
                dt.AcceptChanges();
                ReturnListJson(dt);
                //string jsonStr = "{\"status\":\"0\",\"mes\":\"获取数据成功\",\"data\":[";

                //jsonStr += "{\"sdate\":\"" + dt.Rows[0]["sdate"].ToString() + "\",\"edate\":\"" + dt.Rows[0]["edate"].ToString() + "\",\"checkcode\":\"" + dt.Rows[0]["checkcode"].ToString() + "\",\"couname\":\"" + dt.Rows[0]["couname"].ToString() + "\",\"storename\":\"" + dt.Rows[0]["storename"].ToString() + "\",\"singlemoney\":\"" + dt.Rows[0]["singlemoney"].ToString() + "\",\"maxmoney\":\"" + dt.Rows[0]["maxmoney"].ToString() + "\",\"uselimit\":\"" + dt.Rows[0]["uselimit"].ToString() + "\",\"istodayuse\":\"" + dt.Rows[0]["istodayuse"].ToString() + "\",\"goodsname\":\"" + dt.Rows[0]["goodsname"].ToString() + "\",\"couponimg\":\"" + Helper.GetAppSettings("imgUrl") + path + "\",\"mvtype\":\"" + dt.Rows[0]["mvtype"].ToString() + "\",\"descr\":\"" + dt.Rows[0]["descr"].ToString() + "\"}]}";

                //ToJsonStr(jsonStr);
            }
            else
            {
                ToCustomerJson("2", "网络繁忙,请稍后再试");
            }
        }
Example #35
0
        public static string PerformASPFileUpload(HttpPostedFile file, HttpServerUtility server, string folder)
        {
            if (!Licencing.validate())
                return string.Empty;

            string FileName = file.FileName;
            string newFIleName = Useful_Classes.StringManipulation.GenerateRandomString(25) + "." + FileName.Split('.')[FileName.Split('.').Length - 1];
            string saveFile = server.MapPath(folder + ((folder.Replace("/", "\\").EndsWith("\\")) ? "" : "\\") + newFIleName);

            if (validateFolderExistance(saveFile))
            {
                file.SaveAs(saveFile);

                return newFIleName;
            }

            return string.Empty;
        }
Example #36
0
        /// <summary>
        /// 生成二维码并展示到页面上
        /// </summary>
        /// <param name="precreateResult">二维码串</param>
        public string DoWaitProcess(string ecard)
        {
            //打印出 preResponse.QrCode 对应的条码
            Bitmap bt;

            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();

            qrCodeEncoder.QRCodeEncodeMode   = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
            qrCodeEncoder.QRCodeScale        = 3;
            qrCodeEncoder.QRCodeVersion      = 8;
            bt = qrCodeEncoder.Encode(ecard, Encoding.UTF8);
            string filename = ecard + ".jpg";
            string path     = "/erqimg/" + filename;

            bt.Save(server.MapPath("~" + path));

            return(path);
        }
Example #37
0
        /// <summary>
        /// 获取微信授权ACCESS_TOKEN
        /// </summary>
        public void GetAccessToken(HttpServerUtility server)
        {
            string recvData = Common.Controllers.APIController.SendData("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APIController.APP_ID + "&secret=" + APIController.APP_SECRET, "", "GET", "");
            JavaScriptSerializer java = new JavaScriptSerializer();
            Dictionary<string, object> recvDic = java.Deserialize<Dictionary<string, object>>(recvData);
            Dictionary<string, object> _tempDic = new Dictionary<string, object>();
            int expires_in = Convert.ToInt32(recvDic["expires_in"]);
            _tempDic.Add("access_token", recvDic["access_token"]);
            _tempDic.Add("expires_in", expires_in);
            _tempDic.Add("expires_date", DateTime.Now.AddSeconds(expires_in).ToString());
            StringBuilder output = new StringBuilder();
            java.Serialize(_tempDic, output);

            //写入TOKEN缓存
            APIController.ACCESS_TOKEN = recvDic["access_token"].ToString();

            //写入TOKEN缓存文件
            string path = server.MapPath(APIController.ACCESS_TOKEN_PATH);
            System.IO.File.WriteAllText(path, output.ToString());
        }
        public static void Register(HttpServerUtility server)
        {
            ConstantManager.LogPath = server.MapPath("~/Areas/Admin/LogFiles/");
            ConstantManager.ConfigPath = server.MapPath("~/Areas/Admin/AdminConfig.xml");
            ConstantManager.SavedPath = server.MapPath("~/Areas/Admin/SavedPages");
            ConstantManager.TrainingFilePath = server.MapPath("~/UploadedExcelFiles/ProductNameTraining.txt");
            ConstantManager.TrainingFilePathForProduct = server.MapPath("~/UploadedExcelFiles/ProductNameTraining.txt");
            ConstantManager.NoResultFilePath = server.MapPath("~/Areas/Admin/LogFiles/NoResult/result.txt");
            ConstantManager.DefaultImage = server.MapPath("images/I/default.jpg");
            ConstantManager.IsParserRunning = false;
            ConstantManager.IsRecommendRunning = false;
            ConstantManager.IsUpdateRunning = false;

            ConstantManager.RatioCPUPoint = 1;
            ConstantManager.RatioVGAPoint = 1;
            ConstantManager.RatioRAMPoint = 1;
            ConstantManager.RatioHDDPoint = 1;
            ConstantManager.RatioDisplayPoint = 1;
            ConstantManager.BestScore = 1;
        }
        public static void AddErrorLog(SqlCommand sqlCmd, string exStr)
        {
            try
            {
                System.Web.HttpServerUtility Server = System.Web.HttpContext.Current.Server;
                string fileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";
                string filePath = Server.MapPath("../log/") + fileName;


                DateTime Date = DateTime.Now;

                if (!Directory.Exists(HttpContext.Current.Server.MapPath("../log/")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("../log/"));
                }


                using (StreamWriter sw = File.AppendText(filePath))
                {
                    sw.WriteLine("*----------------------------------------------------------");
                    sw.WriteLine("err_Time:" + Date.ToString("yyyy-MM-dd HH:mm:ss") + "");
                    sw.WriteLine("err_Page:" + HttpContext.Current.Request.Url.AbsoluteUri);
                    sw.WriteLine("err_SqlStr:" + sqlCmd.CommandText + "");
                    sw.WriteLine("err_ComPars:");
                    for (int i = 0; i < sqlCmd.Parameters.Count; i++)
                    {
                        string pStr = "  " + sqlCmd.Parameters[i].ParameterName + ":" + sqlCmd.Parameters[i].Value + "";
                        sw.WriteLine(pStr);
                    }
                    sw.WriteLine("err_ExStr:" + exStr);
                    sw.WriteLine("----------------------------------------------------------*");
                    sw.Flush();
                    sw.Close();
                }
            }
            finally
            {
            }
        }
        public static string GetCodeFileString(HttpServerUtility server, CustomItemInformation info)
        {
            VelocityEngine velocity = new VelocityEngine();

            ExtendedProperties props = new ExtendedProperties();
            props.SetProperty("file.resource.loader.path", server.MapPath(".")); // The base path for Templates

            velocity.Init(props);

            //Template template = velocity.GetTemplate("template.tmp");
            NVelocity.Template template = velocity.GetTemplate("CustomItem.vm");

            VelocityContext context = new VelocityContext();

            context.Put("BaseTemplates", info.BaseTemplates);
            context.Put("CustomItemFields", info.Fields);
            context.Put("CustomItemInformation", info);

            StringWriter writer = new StringWriter();
            template.Merge(context, writer);
            return writer.GetStringBuilder().ToString();
        }
Example #41
0
        public static void Run(HttpServerUtility server, HttpResponse response)
        {
            // 帳票定義ファイルを読み込みます
            Report report = new Report(Json.Read(server.MapPath("report\\example1.rrpt")));

            // 帳票にデータを渡します
            report.Fill(new ReportDataSource(getDataTable()));

            // ページ分割を行います
            ReportPages pages = report.GetPages();

            // PDF出力
            using (Stream _out = response.OutputStream)
            {
                PdfRenderer renderer = new PdfRenderer(_out);
                // バックスラッシュ文字を円マーク文字に変換します
                renderer.Setting.ReplaceBackslashToYen = true;
                pages.Render(renderer);
                response.ContentType = "application/pdf";
                response.AddHeader("Content-Disposition", "attachment;filename=example1.pdf");
                response.End();
            }
        }
Example #42
0
        public ResponseResult PostDocument(dynamic documentObj)
        {
            try
            {
                string _document = Convert.ToString(documentObj.document);

                if (string.IsNullOrEmpty(_document))
                {
                    return(new ResponseResult {
                        Code = 4002, Message = "内容不能为空!"
                    });
                }

                System.Web.HttpServerUtility Server = System.Web.HttpContext.Current.Server;
                string all_path = Server.MapPath("~/Upload");
                if (Directory.Exists(all_path))
                {
                    WriteTxt(all_path + "/Document.txt", _document, false);
                }
                else
                {
                    Directory.CreateDirectory(all_path);
                    WriteTxt(all_path + "/Document.txt", _document, false);
                }

                return(new ResponseResult {
                    Code = 2000, Message = "操作成功!"
                });
            }
            catch (Exception ex)
            {
                return(new ResponseResult {
                    Code = 4001, Message = ex.Message
                });
            }
        }
Example #43
0
        public static System.Drawing.Image PerformASPImageUpload(HttpPostedFile file, HttpServerUtility server, string folder)
        {
            if (!Licencing.validate())
                return null;

            string FileName = file.FileName;
            string saveFile = server.MapPath(folder + ((folder.Replace("/", "\\").EndsWith("\\")) ? "" : "\\") + Useful_Classes.StringManipulation.GenerateRandomString(25) + "." + FileName.Split('.')[FileName.Split('.').Length - 1]);

            if (validateFolderExistance(saveFile))
            {
                file.SaveAs(saveFile);
                System.Drawing.Image IMG = System.Drawing.Image.FromFile(saveFile);

                try
                {
                    File.Delete(saveFile);
                }
                catch { }

                return IMG;
            }

            return null;
        }
Example #44
0
 public static string getSetting(HttpServerUtility app, string name,bool isFile=false)
 {
     if (System.Configuration.ConfigurationManager.AppSettings[name] == null)
     {
         throw new Exception("配置文件不正确:"+name+"!");
     }
     string val= System.Configuration.ConfigurationManager.AppSettings[name].ToString();
     if (isFile) {
         if (val.IndexOf(":") != 1)
         {
             val = app.MapPath(val);
         }
     }
     return val;
 }
Example #45
0
 public static string GetServerMapPath(string FileName)
 {
     return(ServerUtility.MapPath(FileName));
 }
Example #46
0
        public void ProcessRequest(HttpContext context)
        {
            System.Web.HttpRequest       Request  = context.Request;
            System.Web.HttpServerUtility Server   = context.Server;
            System.Web.HttpResponse      Response = context.Response;


            string Image = Request.QueryString["src"];



            object obj = Request.QueryString["fillColor"];

            if (obj != null && obj.ToString() != "")
            {
                _fillColor = Color.FromArgb(Int32.Parse(obj.ToString()));
            }


            int width = 50, height = 50;

            if (Request.QueryString["width"] != null && Request["width"] != "")
            {
                width = Int32.Parse(Request["width"]);
            }

            if (Request["height"] != null && Request["height"] != "")
            {
                height = Int32.Parse(Request["height"]);
            }

            if (width <= 0)
            {
                width = 99999;
            }
            if (height <= 0)
            {
                height = 99999;
            }

            if (!String.IsNullOrEmpty(Request["Crop"]))
            {
                Crop = bool.Parse(Request["Crop"]);
            }

            Image = Server.MapPath("~/" + Image);



            if (!System.IO.File.Exists(Image))
            {
                Response.Write(Image);
                return;
            }

            System.Drawing.Image im = System.Drawing.Image.FromFile(Image);

            //	Response.ContentType = "image/png";

            System.Drawing.Image resp = null;


            if (Crop)
            {
                resp = lw.GraphicUtils.ImageUtils.Crop(im, width, height, lw.GraphicUtils.ImageUtils.AnchorPosition.Default);
            }
            else
            {
                resp = lw.GraphicUtils.ImageUtils.FixedSize(im, width, height);
            }

            //resp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);

            Response.Write(resp);
            Response.End();

            resp.Save(Server.MapPath("~/prv/ballout.png"));

            resp.Dispose();
            im.Dispose();
        }
Example #47
0
        public static string BeetExportConnectionString()
        {
            System.Web.Caching.Cache cache = System.Web.HttpRuntime.Cache;
            object o = cache["BeetExportConnectionString"];

            if (o == null)
            {
                System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
                string s = "Provider=Microsoft.Jet.OLEDB.4.0;User Id=admin;Password=;" + "Data Source=" + server.MapPath(@"~/ZHost/Export/BeetFields.mdb");
                cache["BeetExportConnectionString"] = s;
                return(s);
            }
            else
            {
                return(o.ToString());
            }
        }
Example #48
0
 /// <summary>
 /// See <see cref="HttpServerUtility"/> for a description.
 /// </summary>
 public string MapPath(string path)
 {
     return(_httpServerUtility.MapPath(path));
 }
Example #49
0
 public override string MapPath(string path)
 {
     return(w.MapPath(path));
 }
        public static void sendFormattedMail(
            string fileSpec, Dictionary <string, string> substitutions, string to,
            string subject, bool useWebRequest, System.Web.HttpServerUtility server, string from, LastChanceToDoSomethingWithEmailBeforeItGoesOut hookLastChanceToDoDoSomethingWithEmail, DoSomethingAfterEmailBeforeGoesOut hookAfterSuccessfulEmailTranmission, string localFileSystemFileSpec, Dictionary <string, string> otherStuff)
        {
            lock (DDCommon.CommonRoutines._lockingObject) {
                string text = string.Empty;
                bool   makeItThrowAnException = false; // so's I can test
                if (useWebRequest)
                {
                    StreamReader  sr = null;
                    StringBuilder sa = new StringBuilder();
                    try {
                        byte[] ba                = new byte[1000];
                        char[] ca                = new char[1000];
                        int    nbrRead           = 0;
                        System.Net.WebRequest wr = null;
                        Stream str               = null;
                        bool   isLocalFileSystem = false;
                        try {
                            if (makeItThrowAnException)
                            {
                                throw new Exception("dummy");
                            }
                            wr  = System.Net.WebRequest.Create(fileSpec);
                            str = wr.GetResponse().GetResponseStream();
                        } catch {
                            isLocalFileSystem = true;
                            sr = new StreamReader(localFileSystemFileSpec);
                        }

                        if (!isLocalFileSystem)
                        {
                            nbrRead = str.Read(ba, 0, 1000);
                            // kludge to get rid o weird characters
                            System.Text.Decoder dec = Encoding.Default.GetDecoder();
                            while (nbrRead > 0)
                            {
                                for (int c = 0; c < nbrRead; c++)
                                {
                                    if (ba[c] == 239 || ba[c] == 187 || ba[c] == 191)
                                    {
                                        ba[c] = 32;
                                    }
                                }
                                dec.GetChars(ba, 0, nbrRead, ca, 0);
                                string str2 = new string(ca, 0, nbrRead).Trim();
                                sa.Append(str2);
                                nbrRead = str.Read(ba, 0, 1000);
                            }
                        }
                        else
                        {
                            nbrRead = sr.Read(ca, 0, 1000);
                            while (nbrRead > 0)
                            {
                                // kludge to get rid o weird characters
                                for (int c = 0; c < nbrRead; c++)
                                {
                                    if (ca[c] == 239 || ca[c] == 187 || ca[c] == 191)
                                    {
                                        ca[c] = ' ';
                                    }
                                }
                                sa.Append(ca, 0, nbrRead);
                                nbrRead = sr.Read(ca, 0, 1000);
                            }
                        }
                        text = sa.ToString();
                    } catch {
                    } finally {
                        try {
                            sr.Close();
                        } catch { }
                    }
                }
                else
                {
                    string       path        = server.MapPath(".");
                    string       newFileSpec = path + "\\" + Path.GetFileName(fileSpec);
                    StreamReader sr          = null;
                    try {
                        sr = new StreamReader(newFileSpec);
                        string line     = sr.ReadLine();
                        bool   breakOut = false;
                        if (line == null)
                        {
                            breakOut = true;
                        }
                        while (!breakOut)
                        {
                            text += line;
                            try {
                                line = sr.ReadLine();
                            } catch {
                                breakOut = true;
                                break;
                            }
                            if (line == null)
                            {
                                breakOut = true;
                                break;
                            }
                        }
                    } finally {
                        text.Replace("’", "&rsquo;");
                        text.Replace("‘", "&lsquo;");
                        text.Replace("'", "&apos;");
                        text.Replace("\"", "&quot;");
                        text.Replace("“", "&ldquo;");
                        text.Replace("”", "&rdquo;");
                        text.Replace("Â", " ");
                        sr.Close();
                    }
                }
                foreach (string substitutionKey in substitutions.Keys)
                {
                    text = text.Replace("&&" + substitutionKey, substitutions[substitutionKey]);
                }
                if (from != null)
                {
                    sendMail(from, to, subject, text, true, hookLastChanceToDoDoSomethingWithEmail, hookAfterSuccessfulEmailTranmission, otherStuff);
                }
                else
                {
                    sendMail(to, subject, text, true, hookLastChanceToDoDoSomethingWithEmail, hookAfterSuccessfulEmailTranmission, otherStuff);
                }
            }
        }
        public void AddAttachments(
            Project dbtask, 
            List<HttpPostedFileBase> uploadedAttachments, 
            HttpServerUtility server)
        {
            if (uploadedAttachments == null)
            {
                return;
            }

            if (!Directory.Exists(server.MapPath(TasksConstants.MainContentFolder)))
            {
                Directory.CreateDirectory(server.MapPath(TasksConstants.MainContentFolder));
            }

            if (!Directory.Exists(server.MapPath(TasksConstants.MainContentFolder + "\\" + dbtask.Id)))
            {
                Directory.CreateDirectory(server.MapPath(TasksConstants.MainContentFolder + "\\" + dbtask.Id));
            }

            foreach (var file in uploadedAttachments)
            {
                var filename = Path.GetFileName(file.FileName);
                file.SaveAs(server.MapPath(TasksConstants.MainContentFolder + "\\" + dbtask.Id + "\\" + filename));
                dbtask.Attachments.Add(new Attachment() { Name = file.FileName });

                this.Update(dbtask);
            }
        }