/// <summary>
    /// 取得主視覺的內容
    /// </summary>
    /// <param name="server"></param>
    /// <param name="mainAdvNodeId">主視覺設定檔代碼</param>
    /// <returns>主視覺的內容</returns>
    public static string GetMainAdvContent(HttpServerUtility server, int mainAdvNodeId)
    {
        string content = string.Empty;

        PostFactory postFactory = new PostFactory();
        IPostService postService = postFactory.GetPostService();

        NodeVO nodeVO = postService.GetNodeById(mainAdvNodeId);
        if (nodeVO != null)
        {
            if (nodeVO.UType == NodeVO.UnitType.Flash)
            {
                string advFile = server.MapPath("~/template/") + "main-adv-flash01.txt";
                string fileContent = File.ReadAllText(advFile, System.Text.Encoding.UTF8);

                content = fileContent.Replace("(#FILENAME)", nodeVO.PicFileName);
            }
            //暫時不用圖片,僅flash
            //else if (nodeVO.UType == NodeVO.UnitType.Pic)
            //{
            //    string advFile = server.MapPath("~/template/") + "main-adv-pic01.txt";
            //    string fileContent = File.ReadAllText(advFile, System.Text.Encoding.UTF8);

            //    content = fileContent.Replace("(#FILENAME)", nodeVO.PicFileName);
            //}
        }

        return content;
    }
 private static void CheckTable(GtfsTable gtfsTable, String extension, HttpServerUtility server)
 {
     gtfsTable.FilePath = String.Format("/parsed/{0}{1}", gtfsTable.Name, extension);
     var fileInfo = new FileInfo(server.MapPath(gtfsTable.FilePath));
     gtfsTable.Extension = fileInfo.Extension;
     gtfsTable.Exists = fileInfo.Exists;
     gtfsTable.LastUpdateUtc = fileInfo.LastWriteTimeUtc;
 }
Beispiel #3
0
        /// <summary>
        /// 文件保存操作
        /// </summary>
        /// <param name="basePath"></param>
        private void SaveFile(HttpContext context, string basePath = "/Files/")
        {
            HttpServerUtility  server  = context.Server;
            HttpRequest        request = context.Request;
            HttpFileCollection files   = System.Web.HttpContext.Current.Request.Files;

            string path = basePath;
            string type = string.Empty;

            if (!string.IsNullOrEmpty(request["isType"]))       //跟路径
            {
                type     = request["isType"].ToString();
                basePath = ConfigurationManager.AppSettings[type].ToString();
                path     = server.MapPath(basePath);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }

            if (!string.IsNullOrEmpty(request["isName"]))           //子路径
            {
                string fname = request["isName"].ToString();
                path     = path + fname;
                basePath = basePath + fname;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }

            //后缀名
            var suffix = files[0].ContentType.Split('/')[1];
            //原始文件名称
            //var _temp = System.Web.HttpContext.Current.Request["name"];
            //文件名称
            Random rand = new Random(24 * (int)DateTime.Now.Ticks);
            string name = rand.Next() + "." + suffix;

            //保存全路径
            string normalPath = basePath + "/" + name;
            string fullPath   = path + "/" + name;


            //files[0].SaveAs(fullPath);
        }
Beispiel #4
0
        /// <summary>
        /// Gets a list of all available objects that implement ISerialKeyProvider interface
        /// </summary>
        /// <returns>A list of all available objects that implement ISerialKeyProvider interface</returns>
        public static List <ISerialKeyProvider> GetSerialKeyProviders()
        {
            List <ISerialKeyProvider> providers     = new List <ISerialKeyProvider>();
            List <string>             providerNames = new List <string>();

            if (HttpContext.Current != null)
            {
                HttpServerUtility server = HttpContext.Current.Server;
                string[]          files  = System.IO.Directory.GetFiles(server.MapPath("~/bin"), "*.DLL");
                foreach (System.Reflection.Assembly assemblyInstance in AppDomain.CurrentDomain.GetAssemblies())
                {
                    try
                    {
                        foreach (Type thisType in assemblyInstance.GetTypes())
                        {
                            if ((thisType.IsClass && !thisType.IsAbstract))
                            {
                                foreach (Type thisInterface in thisType.GetInterfaces())
                                {
                                    ISerialKeyProvider instance = null;
                                    if ((!string.IsNullOrEmpty(thisInterface.FullName) && thisInterface.FullName.Equals(typeof(ISerialKeyProvider).FullName)))
                                    {
                                        string classId        = Utility.Misc.GetClassId(thisType);
                                        string loweredClassId = classId.ToLowerInvariant();
                                        if (!providerNames.Contains(loweredClassId))
                                        {
                                            instance = Activator.CreateInstance(Type.GetType(classId)) as ISerialKeyProvider;
                                            if (instance != null)
                                            {
                                                providers.Add(instance);
                                            }
                                            providerNames.Add(loweredClassId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        //ignore error
                    }
                }
            }
            return(providers);
        }
Beispiel #5
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);
        }
        public bool validateUploadData(HttpServerUtility Server)
        {
            string fileName      = Path.GetFileName(myFile.FileName);
            string fileExtension = Path.GetExtension(myFile.FileName);
            string fileLocation  = Server.MapPath("~/App_Data/" + fileName);

            if (File.Exists(fileExtension))
            {
                File.Delete(fileLocation);
            }

            myFile.SaveAs(fileLocation);



            //Check whether file extension is xls or xslx

            if (fileExtension == ".xls")
            {
                // connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";
            }
            else if (fileExtension == ".xlsx")
            {
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                // connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + @";Extended Properties=" + Convert.ToChar(34).ToString() + @"Excel 8.0;Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();
            }

            int nFileLen = myFile.ContentLength;

            if (nFileLen == 0)
            {
                throw new ArgumentNullException("No file was uploaded");
            }


            // Check file extension (must be JPG)
            if (!(System.IO.Path.GetExtension(myFile.FileName).ToLower() == ".xls" || System.IO.Path.GetExtension(myFile.FileName).ToLower() == ".xlsx"))
            {
                throw new ArgumentNullException("Not a Valid Excel File");
            }


            return(true);
        }
Beispiel #7
0
        public static void Write(string LogContent)
        {
            if (!bSwitch || LogContent.ToLower().IndexOf("password") == -1)
            {
                return;
            }

            HttpServerUtility hsu     = HttpContext.Current.Server;
            string            strPath = hsu.MapPath("~/Uploads/SqlLog/");

            StreamWriter sw = null;

            lock (objLock)
            {
                try
                {
                    string strFileName = strPath + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                    sw = new StreamWriter(strFileName, true, Encoding.UTF8);
                    if (LogContent == System.Environment.NewLine)
                    {
                        sw.WriteLine(System.Environment.NewLine);
                    }
                    else
                    {
                        sw.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\r\n-------------------\r\n" + LogContent);
                    }
                    sw.Write("\r\n");
                    sw.Close();
                }
                catch (Exception err)
                {
                    if (sw != null)
                    {
                        sw.Close();
                    }
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Close();
                    }
                }
            }
        }
        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");
            }
        }
        /// <summary>
        /// 执行转换
        /// </summary>
        public void Convert()
        {
            HttpServerUtility Server = HttpContext.Current.Server;

            Process p = new Process();

            p.StartInfo.FileName               = Server.MapPath(@"\App_Data\FlashPaper\FlashPrinter.exe");
            p.StartInfo.Arguments              = InputFile + " -o " + OutputFile;
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardInput  = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError  = true;
            p.StartInfo.CreateNoWindow         = true;
            p.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
            p.Start();
            p.WaitForExit();
            p.Close();
        }
Beispiel #10
0
        /// <summary>
        /// Register user with given Details
        /// </summary>
        /// <param name="userName">UserName</param>
        /// <param name="password">Password</param>
        /// <param name="name">Full Name</param>
        /// <param name="email">Email Address</param>
        /// <param name="address">Full Address</param>
        /// <param name="role">Role: User/Admin</param>
        /// <returns>Returns true if sucessfull, false if user exists</returns>
        public bool RegisterUser(string userName, string password, string name, string email, string address, string role)
        {
            //Checks if the user already exists
            if (UserExists(userName))
            {
                return(false);
            }

            //Generate salt and hashed password
            var salt       = GenerateSalt();
            var hashedPass = HashPassword(password.Trim() + salt);

            //Add user data to the database and write the xml file
            userDb.User.AddUserRow(userName.Trim(), name.Trim(), email.Trim(), hashedPass, address.Trim(), salt, role.Trim());
            userDb.User.WriteXml(Server.MapPath(UserPath));

            return(true);
        }
Beispiel #11
0
        public void ProcessRequest(HttpContext context)
        {
            HttpResponse      oResponse = HttpContext.Current.Response;
            HttpServerUtility oServer   = HttpContext.Current.Server;

            string sPath = oServer.MapPath("/Resources") + "\\Mattel Manual Licenciatarios.pdf";

            oResponse.ContentType = "application/pdf";
            oResponse.AppendHeader("Content-Disposition", "attachment; filename=Mattel Manual Licenciatarios.pdf");

            // Write the file to the Response
            const int bufferLength = 10000;

            byte[] buffer   = new Byte[bufferLength];
            int    length   = 0;
            Stream download = null;

            try
            {
                download = new FileStream(sPath, FileMode.Open, FileAccess.Read);
                do
                {
                    if (oResponse.IsClientConnected)
                    {
                        length = download.Read(buffer, 0, bufferLength);
                        oResponse.OutputStream.Write(buffer, 0, length);
                        buffer = new Byte[bufferLength];
                    }
                    else
                    {
                        length = -1;
                    }
                }while (length > 0);
                oResponse.Flush();
                oResponse.End();
            }
            finally
            {
                if (download != null)
                {
                    download.Close();
                }
            }
        }
        public void upload()
        {
            string      token       = _request.QueryString["token"];
            UploadToken uploadToken = GetTokenInfo(token);

            if (uploadToken != null && uploadToken.size > uploadToken.upsize)
            {
                Stream stream = _request.InputStream;
                if (stream != null && stream.Length > 0)
                {
                    _fileHelper.FileName = uploadToken.name;
                    _fileHelper.FilePath = _server.MapPath(_filePath);
                    _fileHelper.WriteFile(stream);

                    uploadToken.upsize += stream.Length;
                    if (uploadToken.size > uploadToken.upsize)
                    {
                        SetTokenInfo(token, uploadToken);
                    }
                    else
                    {
                        //上传完成后删除令牌信息
                        DelTokenInfo(token);

                        //重命名(解决重复上传时内容叠加)
                        //FileInfo fileinfo = new FileInfo(_server.MapPath(_filePath) + uploadToken.name);
                        //string Rename = string.Format(@"{0}_{1}{2}", Path.GetFileNameWithoutExtension(fileinfo.FullName), DateTime.Now.ToString("mmssffff"), fileinfo.Extension);
                        //fileinfo.MoveTo(_server.MapPath(_filePath) + Rename);
                        //uploadToken.name = Rename;

                        //无需重命名
                        uploadToken.name = uploadToken.name;
                    }
                }
            }
            UploadResult ur = new UploadResult();

            ur.message  = "";
            ur.filePath = HttpUtility.UrlEncode(_filePath + uploadToken.name, Encoding.UTF8);
            ur.start    = uploadToken.upsize;
            ur.success  = true;

            string result = JSONHelper.SerializeObject(ur);

            _response.Write(result);
        }
Beispiel #13
0
        //Constructor
        public ShaderMaster()
        {
            string folder = server.MapPath("/App/Shaders");
            var    files  = Directory.GetFiles(folder);

            string[] shaders;

            foreach (var file in files)
            {
                if (Path.GetExtension(file).ToLower() == ".txt")
                {
                    shaders = File.ReadAllText(file).Split(new string[] { "//Vert", "//Frag" }, StringSplitOptions.RemoveEmptyEntries);
                    string name = Path.GetFileName(file).Split('.')[0];

                    BmMaterial mat = new BmMaterial(name, shaders[0], shaders[1]);
                    materials.Add(mat);
                }
            }
        }
Beispiel #14
0
        public static void WriteErrorLog(Exception ex)
        {
            try
            {
                if (ex != null)
                {
                    string content = "类型:" + Types.GetTypeByID(TypeConfigs.GetLogError).Name + "\r\n";
                    content += "时间:" + DateTime.Now.ToString() + "\r\n";
                    content += "来源:" + ex.TargetSite.ReflectedType.ToString() + "." + ex.TargetSite.Name + "\r\n";
                    content += "内容:" + ex.Message + "\r\n";
                    if (BaseConfigs.GetLogInDB == 1)
                    {
                        Log log = new Log();
                        log.Content = content;
                        log.Type    = TypeConfigs.GetLogError;
                        Data.Logs.CreateLog(log);
                    }
                    if (BaseConfigs.GetLogInFile == 1)
                    {
                        Page page = new Page();
                        HttpServerUtility server = page.Server;
                        string            dir    = server.MapPath(BaseConfigs.GetLogFilePath);


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

                        string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

                        StreamWriter FileWriter = new StreamWriter(path, true); //创建日志文件
                        FileWriter.Write("---------------------------------------------------\r\n");
                        FileWriter.Write(content);
                        FileWriter.Close(); //关闭StreamWriter对象
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
    public static string GetMainTopAdvPic(HttpServerUtility server, int m_PostId1)
    {
        string content = string.Empty;

        WebPageHelper webPageHelper = new WebPageHelper();
        PostFactory postFactory = new PostFactory();
        IPostService postService = postFactory.GetPostService();

        PostVO podeVO = postService.GetPostById(m_PostId1);
        if (podeVO != null)
        {
            string advFile = server.MapPath("~/template/") + "main-adv-pic01.txt";
            string fileContent = File.ReadAllText(advFile, System.Text.Encoding.UTF8);

            content = fileContent.Replace("(#FILENAME)", webPageHelper.GetContent(podeVO, "PicFileName"));
        }

        return content;
    }
Beispiel #16
0
        public static void Register(HttpServerUtility server)
        {
            var thisAssembly             = typeof(SwaggerConfig).Assembly;
            var swaggerDocumentationPath = server.MapPath("~/bin/Middleware.Wm.Service.Inventory.Swagger.xml");

            GlobalConfiguration.Configuration
            .EnableSwagger(c =>
            {
                c.ApiKey("AuthenticationToken")
                .Description("Token provided by New Balance to authorize access to the service.")
                .Name("AuthenticationToken")
                .In("header");

                c.SingleApiVersion("v1", "Middleware.Inventory");
                c.IncludeXmlComments(swaggerDocumentationPath);
                c.DescribeAllEnumsAsStrings();
            })
            .EnableSwaggerUi(c => { });
        }
Beispiel #17
0
        public static PrenumeratoriuSarasas NuskaitymasB(string failas, HttpServerUtility Server)
        {
            PrenumeratoriuSarasas sarasas = new PrenumeratoriuSarasas();

            string[] eilutes = File.ReadAllLines(Server.MapPath(failas));
            foreach (string eilute in eilutes)
            {
                string[]        dalys              = eilute.Split(',');
                string          pavarde            = dalys[0];
                string          adresas            = dalys[1];
                int             laikotarpioPradzia = int.Parse(dalys[2]);
                int             laikotarpioIlgis   = int.Parse(dalys[3]);
                int             kodas              = int.Parse(dalys[4]);
                int             kiekis             = int.Parse(dalys[5]);
                Prenumeratorius prenumeratorius    = new Prenumeratorius(pavarde, adresas, laikotarpioPradzia, laikotarpioIlgis, kodas, kiekis);
                sarasas.DetiDuomenisA(prenumeratorius);
            }
            return(sarasas);
        }
Beispiel #18
0
        /// <summary>
        /// 用于替代 Server.MapPath 方法,保证代码的可测试性
        /// </summary>
        /// <param name="server"></param>
        /// <param name="virtualPath"></param>
        /// <returns></returns>
        public static string GetMappingPath(this HttpServerUtility server, string virtualPath)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            if (IsTestEnvironment)
            {
                HttpContext context = (HttpContext)typeof(HttpServerUtility).GetInstanceField("_context").GetValue(server);
                // 为了兼容一些家伙们的错误写法,这里先做个斜杠的转换。
                return(InternalMapPath(context.Request, virtualPath.Replace("\\", "/")));
            }

            else
            {
                return(server.MapPath(virtualPath));
            }
        }
Beispiel #19
0
        public static void InitImageHelpers(HttpServerUtility server)
        {
            string path = server.MapPath("~/Images/");

            var fileStream = new FileStream(path + UIConsts.DefaultMaleImage, FileMode.Open);
            var memStream  = new MemoryStream();

            memStream.SetLength(fileStream.Length);
            fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
            fileStream.Close();
            _defaultMaleStream = memStream;

            fileStream = new FileStream(path + UIConsts.DefaultFemaleImage, FileMode.Open);
            memStream  = new MemoryStream();
            memStream.SetLength(fileStream.Length);
            fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
            fileStream.Close();
            _defaultFemaleStream = memStream;
        }
        public static void WriteErrorLog(Exception ex)
        {
            try
            {
                if (ex != null)
                {
                    string content = "类型:错误代码\r\n";
                    content += "时间:" + DateTime.Now.ToString() + "\r\n";
                    content += "来源:" + ex.TargetSite.ReflectedType.ToString() + "." + ex.TargetSite.Name + "\r\n";
                    content += "内容:" + ex.Message + "\r\n";
                    //if (BaseConfigs.GetLogInDB == 1)
                    //{
                    //TSysLog log = new TSysLog();
                    //log.Content = content;
                    //log.Type = "系统日志";
                    //log.CreateTime = DateTime.Now;
                    //DataAccess.CreateSysLog().Add(log);
                    //}
                    //if (BaseConfigs.GetLogInFile == 1)
                    //{
                    Page page = new Page();
                    HttpServerUtility server = page.Server;
                    string            dir    = server.MapPath("/App_Data/Log/");
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

                    StreamWriter FileWriter = new StreamWriter(path, true, System.Text.Encoding.UTF8); //创建日志文件
                    FileWriter.Write("---------------------------------------------------\r\n");
                    FileWriter.Write(content);
                    FileWriter.Close(); //关闭StreamWriter对象
                    //}
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
        private void CommonCode(HttpServerUtility server, string tildeFilePath)
        {
            _path = tildeFilePath;

            if (_path[0] != '~')
            {
                return;
            }

            if (!SourceTools.OKtoServe(tildeFilePath, true))
            {
                return;
            }

            try
            {
                string   filePath = server.MapPath(tildeFilePath);
                FileInfo info     = new FileInfo(filePath);
                _size  = info.Length;
                _date  = info.MostRecentTime();
                _valid = true;

                int  category = FileTools.GetFileCategory(_path);
                bool image    = category == FileTools.IMAGE;

                if (image)
                {
                    using (FileStream stream =
                               new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        try
                        {
                            Bitmap bitmap = new Bitmap(stream);
                            _width  = bitmap.Width;
                            _height = bitmap.Height;
                        }
                        catch { }
                    }
                }
            }
            catch { }
        }
Beispiel #22
0
        private string GetRouteFile(tblDocumento x)
        {
            eSystemModules   Modulo          = (eSystemModules)x.IdTipoDocumento;
            eEstadoDocumento EstadoDocumento = (eEstadoDocumento)x.IdEstadoDocumento;

            string _CodigoInforme = string.Format("{0}_{1}_{2}_{3}_{4}.{5}", Modulo.ToString(), x.IdEmpresa.ToString(), x.NroDocumento.ToString("#000"), (EstadoDocumento == eEstadoDocumento.Certificado ? x.FechaEstadoDocumento.ToString("MM-yyyy") : DateTime.Now.ToString("MM-yyyy")), x.VersionOriginal ?? 1, x.NroVersion);
            string _FileName      = string.Format("{0}.pdf", _CodigoInforme.Replace("-", "_"));
            //string _pathFile = string.Format("https://www.BcmWeb_30.net/PDFDocs/{0}", _FileName);
            HttpServerUtility _Server     = HttpContext.Current.Server;
            string            _MapPath    = _Server.MapPath(".");
            string            _ServerPath = _MapPath.Substring(0, _MapPath.ToLowerInvariant().IndexOf("api"));
            string            _pathFile   = String.Format("{0}PDFDocs\\{1}", _ServerPath, _FileName);

            if (!File.Exists(_pathFile))
            {
                _pathFile = string.Empty;
            }

            return(_pathFile);
        }
Beispiel #23
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);
        }
    public static string GetMainTopAdvPic(HttpServerUtility server, int m_PostId1)
    {
        string content = string.Empty;

        WebPageHelper webPageHelper = new WebPageHelper();
        PostFactory   postFactory   = new PostFactory();
        IPostService  postService   = postFactory.GetPostService();

        PostVO podeVO = postService.GetPostById(m_PostId1);

        if (podeVO != null)
        {
            string advFile     = server.MapPath("~/template/") + "main-adv-pic01.txt";
            string fileContent = File.ReadAllText(advFile, System.Text.Encoding.UTF8);

            content = fileContent.Replace("(#FILENAME)", webPageHelper.GetContent(podeVO, "PicFileName"));
        }

        return(content);
    }
Beispiel #25
0
        public static void Configure(HttpServerUtility server)
        {
            var master = new SqlConnectionStringBuilder
            {
                DataSource         = @"(LocalDB)\MSSQLLocalDB",
                InitialCatalog     = "master",
                IntegratedSecurity = true
            };

            string fileName     = server.MapPath("~/App_Data/Mathematicians.mdf");
            string databaseName = "Mathematicians";
            var    evolver      = new DatabaseEvolver(
                databaseName,
                fileName,
                master.ConnectionString,
                new Genome());

            evolver.DevolveDatabase();
            evolver.EvolveDatabase();
        }
Beispiel #26
0
    public Album findById(int id, HttpServerUtility Server)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("/App_Data/data.xml"));

        XmlNodeList nodeList = doc.GetElementsByTagName("album");
        foreach (XmlNode node in nodeList)
        {
            if (node["id"].InnerText == id.ToString())
            {
                return new Album(
                    id,
                    node["artist"].InnerText,
                    node["title"].InnerText,
                    decimal.Parse(node["price"].InnerText)
                    );
            }
        }
        return null;
    }
Beispiel #27
0
    public MatlabRunner(HttpServerUtility Server, HttpApplicationState Application)
    {
        m_server = Server;
        m_app = Application;

        m_matlab = new EngMATLib.EngMATAccess();
        m_matlab.Evaluate("cd('" + m_server.MapPath("App_Data") + "');");

        m_queue = new Queue<FmriRequest>();
        m_doneList = new List<FmriRequest>();

        m_newItemEvent = new AutoResetEvent(false);
        m_stopEvent = new ManualResetEvent(false);
        m_waitables = new WaitHandle[] { m_newItemEvent, m_stopEvent };

        m_app["ReqHist"] = readFromHistory();

        m_thread = new Thread(WorkLoop);
        m_thread.Start();
    }
Beispiel #28
0
    public MatlabRunner(HttpServerUtility Server, HttpApplicationState Application)
    {
        m_server = Server;
        m_app    = Application;

        m_matlab = new EngMATLib.EngMATAccess();
        m_matlab.Evaluate("cd('" + m_server.MapPath("App_Data") + "');");

        m_queue    = new Queue <FmriRequest>();
        m_doneList = new List <FmriRequest>();

        m_newItemEvent = new AutoResetEvent(false);
        m_stopEvent    = new ManualResetEvent(false);
        m_waitables    = new WaitHandle[] { m_newItemEvent, m_stopEvent };

        m_app["ReqHist"] = readFromHistory();

        m_thread = new Thread(WorkLoop);
        m_thread.Start();
    }
    public static string GenerateDirectory(string Module, int Type, string template, int PortalId, HttpServerUtility Server, bool CheckDirExist)
    {
        string path = "";

        string[] pathLst = GetPathList(Module, Type, PortalId);
        if (pathLst.Length == 0)
        {
            return("");
        }
        path = pathLst[0];
        foreach (string item in pathLst)
        {
            if (!CheckDirExist || Directory.Exists(Server.MapPath(item)))
            {
                path = item + template;
                break;
            }
        }
        return(path);
    }
        public static DataTable loadUnselectedTeams(HttpServerUtility theserver)
        {
            string DB = theserver.MapPath(SETPATH);

            dbConnect = new OleDbConnection(CONNECTSTRING + DB);

            OleDbDataAdapter dbadapter;
            DataSet          clubdataset;

            OleDbCommand olecommand = new OleDbCommand("getUnselectedTeams", dbConnect);

            olecommand.CommandType = CommandType.StoredProcedure;

            dbadapter = new OleDbDataAdapter(olecommand);

            clubdataset = new DataSet();
            dbadapter.Fill(clubdataset, "clubsdata");

            return(clubdataset.Tables["clubsdata"]);
        }
Beispiel #31
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);
        }
Beispiel #32
0
        /// <summary>
        /// Returns the directory path
        /// corresponding to this server object
        /// and adds a trailing back slash if need be.
        ///
        /// Returns an empty string if an error occurs.
        /// </summary>
        /// <param name="page">A web site HttpServerUtility object</param>
        /// <returns>The associated directory</returns>
        public static string GetDirectoryPath(HttpServerUtility server)
        {
            if (server == null)
            {
                return("");
            }

            string result = server.MapPath("");

            int n = result.Length;

            if (n > 0)
            {
                if (result[n - 1] != backslash)
                {
                    result += backslash;
                }
            }

            return(result);
        }
        /// <summary>
        /// Guarda la imagen en una ruta especifica del servidor
        /// </summary>
        /// <param name="file">Archivo a guardar</param>
        /// <param name="server"></param>
        /// <param name="size">Tamaño de la imagen a guardar</param>
        /// <param name="folder">Ruta en el servidor</param>
        /// <returns>Ruta del de la imagen</returns>
        public static string SaveImageToServer(this HttpPostedFileBase file, HttpServerUtility server, int size = 320, string folder = null)
        {
            var result = string.Empty;

            if (file != null && file.ContentLength != 0)
            {
                var guid = Guid.NewGuid().ToString().Split('-')[0];
                result = guid + "_" + Path.GetFileName(file.FileName);
                var path = server.MapPath(folder ?? "~/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var image = System.Drawing.Image.FromStream(file.InputStream);
                image = image.GetThumbnailImage(size, (size * (image.Height / image.Width).ToDecimal()).ToInteger(), null, IntPtr.Zero);
                image.Save(Path.Combine(path, result));
                image.Dispose();
            }
            return(result);
        }
Beispiel #34
0
        internal static void Initialize(HttpServerUtility server)
        {
            _factory = new SQLiteFactory();

            var builder = (SQLiteConnectionStringBuilder)_factory.CreateConnectionStringBuilder();

            builder.DataSource    = server.MapPath(DatabasePath);
            builder.FailIfMissing = false;

            _connectionString = builder.ConnectionString;

            _connection = (SQLiteConnection)_factory.CreateConnection();
            _connection.ConnectionString = _connectionString;
            _connection.Open();

            using (var cmd = _connection.CreateCommand())
            {
                cmd.CommandText = "CREATE TABLE IF NOT EXISTS report (id INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT NOT NULL, name TEXT NOT NULL, created_at INTEGER NOT NULL, created_by TEXT NOT NULL, contents BLOB NOT NULL)";
                cmd.ExecuteNonQuery();
            }
        }
        public static Team[] loadTeamCartOfTeams(HttpServerUtility theserver)
        {
            string DB = theserver.MapPath(SETPATH);

            dbConnect = new OleDbConnection(CONNECTSTRING + DB);

            OleDbDataAdapter dbadapter;
            DataSet          clubdataset;

            OleDbCommand olecommand = new OleDbCommand("getTeamCart", dbConnect);

            olecommand.CommandType = CommandType.StoredProcedure;

            dbadapter = new OleDbDataAdapter(olecommand);

            clubdataset = new DataSet();
            dbadapter.Fill(clubdataset, "clubsdata");

            DataTable teamsTable = clubdataset.Tables["clubsdata"];

            int recordCount = teamsTable.Rows.Count;

            Team[] theTeams = new Team[recordCount];

            CurrentStatus nowStatus = new CurrentStatus();

            for (int i = 0; i < recordCount; i++)
            {
                theTeams[i]            = new Team();
                theTeams[i].sCurveRank = Convert.ToInt32(teamsTable.Rows[i]["SCurveRank"]);
                theTeams[i].teamName   = teamsTable.Rows[i]["TeamName"].ToString();
                theTeams[i].bracket    = teamsTable.Rows[i]["Bracket"].ToString();
                theTeams[i].rank       = Convert.ToInt32(teamsTable.Rows[i]["TeamRank"].ToString());
                theTeams[i].wins       = Convert.ToInt32(teamsTable.Rows[i]["TeamWins"].ToString());
                theTeams[i].losses     = Convert.ToInt32(teamsTable.Rows[i]["TeamLosses"].ToString());
                theTeams[i].cost       = Convert.ToInt32(teamsTable.Rows[i]["Cost"]);
            }

            return(theTeams);
        }
 private static void AssignLastUpdate(GtfsFile gtfs, HttpServerUtility server)
 {
     gtfs.LastUpdateUtc = new FileInfo(server.MapPath(gtfs.FileName)).LastWriteTimeUtc;
 }
Beispiel #37
0
 public static string getCliquesDir(HttpServerUtility Server)
 {
     return Server.MapPath(@"Cliques") + "\\";
 }
    public static void TemplateDataBind(string Module, int Type, DropDownList ddlTemplate, int PortalId, string LocalResourceFile, HttpServerUtility Server)
    {
        if (Type > 0)
        {
            ddlTemplate.Items.Clear();
            ddlTemplate.Items.Add(new ListItem(Localization.GetString("selectTemplate", LocalResourceFile), ""));
            string path = TemplateEditorUtils.GenerateDirectory(Module, Type, ddlTemplate.SelectedValue, PortalId, Server);
            if (!string.IsNullOrEmpty(path) && Directory.Exists(Server.MapPath(path)))
            {
                var dryLst = Directory.GetDirectories(Server.MapPath(path));

                foreach (string item in dryLst)
                {
                    int nb = item.LastIndexOf('\\');
                    ddlTemplate.Items.Add(item.Substring(nb + 1));
                }
            }
        }
        else
        {
            ddlTemplate.Items.Clear();
            ddlTemplate.Items.Add(new ListItem(Localization.GetString("selectTemplate", LocalResourceFile), ""));
        }
    }
Beispiel #39
0
 /// <summary>
 /// LargeIMGPath原图路径,IMGPath缩略图路径,pathIndex指定路径前缀,pathMid指定路径嵌入字符以区分原图或缩略图
 /// </summary>
 /// <param name="LargeIMGPath"></param>
 /// <param name="IMGPath"></param>
 /// <param name="Server"></param>
 /// <param name="fu"></param>
 /// <param name="pathIndex"></param>
 /// <param name="pathMid"></param>
 public static void uploadIMG(ref string LargeIMGPath, ref string IMGPath, HttpServerUtility Server, HttpPostedFile PostedFile, string FileName, string pathIndex, string pathMid)
 {
     try
     {
         string CurrentDatatime = Convert.ToString(System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString());
         //保存原图
         LargeIMGPath = pathIndex + CurrentDatatime + pathMid + FileName.ToString();
         LargeIMGPath = LargeIMGPath.Replace("%", "");
         string Large_IMG_FullName = Server.MapPath(pathIndex) + CurrentDatatime + pathMid + FileName.ToString();
         Large_IMG_FullName = Large_IMG_FullName.Replace("%", "");
         PostedFile.SaveAs(Large_IMG_FullName);
         //生成缩略图并保存
         IMGPath = pathIndex + CurrentDatatime + FileName.ToString();
         IMGPath=IMGPath.Replace("%", "");
         string IMG_FullName = Server.MapPath(pathIndex) + CurrentDatatime + FileName.ToString();
         IMG_FullName = IMG_FullName.Replace("%", "");
         Thumbnail.MakeThumbnail(Large_IMG_FullName, IMG_FullName, 300, 300, Enums.ImageThumbnail.HWC);
     }
     catch
     {
         throw new Exception("上传文件失败!");
     }
 }
Beispiel #40
0
 public static string getMatrixDir(HttpServerUtility Server)
 {
     return Server.MapPath(@"App_Data\Matrix") + "\\";
 }
Beispiel #41
0
 public static string getOutImageDir(HttpServerUtility Server)
 {
     return Server.MapPath(@"Results") + "\\";
 }
Beispiel #42
0
 public static string getSrcImageDir(HttpServerUtility Server)
 {
     return Server.MapPath(@"App_Data\Images") + "\\";
 }
Beispiel #43
0
 public static void deleteIMG(string IMGPath, HttpServerUtility Server)
 {
     if (IMGPath != null || IMGPath != "")
         try
         {
             string path = Server.MapPath(IMGPath);
             FileInfo fi = new FileInfo(path);
             if (fi.Exists)//如果存在
             {
                 //删除文件.
                 fi.Delete();
             }
         }
         catch (Exception error)
         {
         }
 }
Beispiel #44
0
 public static string getJarFilename(HttpServerUtility Server)
 {
     return Server.MapPath(@"resources") + "\\All_Cliques2.jar";
 }
    public static void ModuleDataBind(DropDownList ddlModule, int PortalId, string LocalResourceFile, HttpServerUtility Server)
    {
        ddlModule.Items.Clear();
        ddlModule.Items.Add(Localization.GetString("selectModule", LocalResourceFile));

        DesktopModuleController mc = new DesktopModuleController();
        var dtmLst = DesktopModuleController.GetDesktopModules(PortalId).Values.Where(m => !m.IsAdmin && !m.FolderName.StartsWith("Admin"));
        foreach (DesktopModuleInfo dtm in dtmLst)
        {
            bool TemplateExist = false;
            for (int i = 1; i < 4; i++)
            {
                string[] pathLst = GetPathList(dtm.FolderName, i, PortalId);
                foreach (string pathitem in pathLst)
                {
                    if (Directory.Exists(Server.MapPath(pathitem)))
                    {
                        ddlModule.Items.Add(new ListItem(dtm.FriendlyName, dtm.FolderName));
                        TemplateExist = true;
                        break;
                    }
                }
                if (TemplateExist) break;
            }
        }
        ddlModule.Items.Add(new ListItem("Skins", "skins"));
        ddlModule.Items.Add(new ListItem("Containers", "containers"));
        ddlModule.Items.Add(new ListItem("Widgets", "widgets"));
    }
Beispiel #46
0
 public static string getExcelDir(HttpServerUtility Server)
 {
     return Server.MapPath(@"Excel") + "\\";
 }
Beispiel #47
0
    /// <summary>
    /// Gets the current folder path for the customer with the specified username and job ID.
    /// </summary>
    /// <param name="username">The username to get a folder path for.</param>
    /// <param name="jobID">The Job ID to get the folder path for.</param>
    /// <returns>A string indicating the current folder path.</returns>
    public static string GetFolderPath(string username, int jobID, HttpServerUtility server)
    {
        string folderPath = server.MapPath("..\\Images\\");

        /* -Get the username
         * -Check if he's part of a company
         * -If yes, get/create company folder
         * -If no, get/create user folder
         * -Get the current year
         * -Get/Create current year folder
         * -Get the name of the current month
         * -Get/Create current month folder
         * -Get the job object
         * -Get/create job object folder
         * -Concatenate all into return string
         * -Return string
         * -Pray
         */
        aspnet_Users user = Brentwood.LookupCustomerByUsername(username);
        if (user.CompanyID == null)
            folderPath = GetOrCreateFolder(folderPath + user.UserName);
        else
        {
            Company company = Brentwood.GetCompanyByCustomerId(user.UserId);
            folderPath = GetOrCreateFolder(folderPath + company.Name);
        }

        string year = DateTime.Today.ToString("yyyy");
        folderPath = GetOrCreateFolder(folderPath + "\\" + year);

        string currentMonth = DateTime.Today.ToString("MMM");
        folderPath = GetOrCreateFolder(folderPath + "\\" + currentMonth);

        Job job = Brentwood.GetJob(jobID);
        JobType jobType = Brentwood.GetJobTypeByJob(jobID);
        string date = DateTime.Today.ToString("dd");
        date += DateTime.Now.ToString("-HH-mm");
        string folder = jobType.Name + "_" + date;
        folderPath = GetOrCreateFolder(folderPath + "\\" + folder);

        return folderPath;
    }
    public static void TemplateDataBind(string Module, DropDownList ddlTemplate, int PortalId, string LocalResourceFile, HttpServerUtility Server)
    {
        ddlTemplate.Items.Clear();
        ddlTemplate.Items.Add(new ListItem(Localization.GetString("selectTemplate", LocalResourceFile), ""));
        for (int type = 1; type < 4; type++)
        {
            string path = TemplateEditorUtils.GenerateDirectory(Module, type, "", PortalId, Server);
            if (!string.IsNullOrEmpty(path) && Directory.Exists(Server.MapPath(path)))
            {
                var dryLst = Directory.GetDirectories(Server.MapPath(path));
                if (dryLst.Count() > 0 && (Directory.GetFiles(Server.MapPath(path)).Count() == 0 || Module == "Blog"))
                {
                    foreach (string item in dryLst)
                    {
                        int nb = item.LastIndexOf('\\');
                        ddlTemplate.Items.Add(new ListItem(GetTypes()[type] + " - " + item.Substring(nb + 1), ReverseMapPath(item)));
                    }
                }
                else
                {
                    ddlTemplate.Items.Add(new ListItem(GetTypes()[type], path));

                }
            }
        }
        if (ddlTemplate.Items.Count == 2) {
            ddlTemplate.Items.RemoveAt(0);
            ddlTemplate.SelectedIndex = 0;
        }
    }
 public static void FileDataBind(string Module, DropDownList ddlTemplate, DropDownList ddlFile, int PortalId, string LocalResourceFile, HttpServerUtility Server)
 {
     ddlFile.Items.Clear();
     ddlFile.Items.Add(new ListItem(Localization.GetString("selectFile", LocalResourceFile), ""));
     string dir = Server.MapPath(ddlTemplate.SelectedValue);
     if (!string.IsNullOrEmpty(ddlTemplate.SelectedValue) && Directory.Exists(dir))
     {
         var fileLst = GetFiles(dir, new string[] { ".cshtml", ".liquid", ".html", ".htm" });
         foreach (string item in fileLst)
         {
             int nb = item.LastIndexOf('\\');
             ddlFile.Items.Add(item.Substring(nb + 1));
         }
     }
 }
Beispiel #50
0
 /// <summary>
 /// IMGPath图路径,pathIndex指定路径前缀
 /// </summary>
 /// <param name="IMGPath"></param>
 /// <param name="Server"></param>
 /// <param name="fu"></param>
 /// <param name="pathIndex"></param>
 public static void uploadIMG(ref string IMGPath, HttpServerUtility Server, HttpPostedFile PostedFile, string FileName, string pathIndex)
 {
     try
     {
         string CurrentDatatime = Convert.ToString(System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString());
         IMGPath = pathIndex + CurrentDatatime + FileName.ToString();
         string IMG_FullName = Server.MapPath(pathIndex) + CurrentDatatime + FileName.ToString();
         IMG_FullName = IMG_FullName.Replace("%", "");
         PostedFile.SaveAs(IMG_FullName);
     }
     catch
     {
     }
 }
    public static string GenerateDirectory(string Module, int Type, string template, int PortalId, HttpServerUtility Server, bool CheckDirExist)
    {
        string path = "";

        string[] pathLst = GetPathList(Module, Type, PortalId);
        if (pathLst.Length == 0) return "";
        path = pathLst[0];
        foreach (string item in pathLst)
        {
            if (!CheckDirExist || Directory.Exists(Server.MapPath(item)))
            {
                path = item + template;
                break;
            }
        }
        return path;
    }