Example #1
0
        private void RunSql()
        {
            StringBuilder  stringBuilder = new StringBuilder();
            BaseConfigInfo baseConfig    = BaseConfigInfo.Current;
            string         mapPath       = Utils.GetMapPath(this.upgradedir + "/sql.config");

            if (!File.Exists(mapPath))
            {
                mapPath = Utils.GetMapPath(BaseConfigs.GetForumPath.ToLower() + "upgrade/" + this.ver + "/sql.config");
            }
            using (StreamReader streamReader = new StreamReader(mapPath, Encoding.UTF8))
            {
                stringBuilder.Append(streamReader.ReadToEnd());
                streamReader.Close();
            }
            string[] array = stringBuilder.Replace("dnt_", baseConfig.Tableprefix).ToString().Trim().Split(new string[]
            {
                "GO\r\n",
                "go\r\n"
            }, StringSplitOptions.RemoveEmptyEntries);
            string[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                string text = array2[i];
                if (!(text.Trim() == ""))
                {
                    try
                    {
                        Databases.RunSql(text);
                    }
                    catch (Exception ex)
                    {
                        base.Response.Write(ex.Message);
                    }
                }
            }
        }
Example #2
0
 protected void btnok_Click(object sender, System.EventArgs e)
 {
     if (!base.IsAuthorizedOp(ActionType.Modify.ToString()))
     {
         base.ShowMsg("Không có thẩm quyền");
     }
     else
     {
         BaseConfigInfo baseConfigInfo = ConfigProvider.GetCacheBaseConfig();
         if (baseConfigInfo == null)
         {
             baseConfigInfo = new BaseConfigInfo();
         }
         baseConfigInfo.UserNameRule        = WebUtils.GetString(this.TextBox2.Text);
         baseConfigInfo.SysUserName         = WebUtils.GetString(this.TextBox3.Text);
         baseConfigInfo.RegAgreement        = StringUtils.ChkSQL(this.TextBox6.Text);
         baseConfigInfo.RegGiveIntegral     = WebUtils.GetInt(this.TextBox7.Text, 10);
         baseConfigInfo.TgIntegral          = WebUtils.GetInt(this.TextBox8.Text, 50);
         baseConfigInfo.VerifycodeForReg    = this.CheckBox1.Checked;
         baseConfigInfo.VerifycodeForLogin  = this.CheckBox2.Checked;
         baseConfigInfo.VerifycodeForGetPwd = this.CheckBox3.Checked;
         baseConfigInfo.TryLoginTimes       = WebUtils.GetInt(this.TextBox9.Text, 5);
         baseConfigInfo.CookieTime          = this.RadioButtonList10.SelectedValue;
         if (ConfigProvider.Update(baseConfigInfo))
         {
             CacheUtils.Del("JsonLeeCMS_CacheForGetBaseConfig");
             CacheUtils.Del("JsonLeeCMS_CacheForVER");
             PageBase.log.AddEvent(base.LoginAccount.AccountName, "更新会员配置成功");
             base.ShowMsg("Cập nhật thành công");
         }
         else
         {
             base.ShowMsg("Cập nhật thất bại");
         }
     }
 }
Example #3
0
 [SoapHeader("header")] //用户身份验证的soap header
 public string CopyTableDataFromCloneSite(string fromPath, string toPath, List <string> tables)
 {
     //验证是否有权访问(当然,也可以通过查询数据库实现,具体视项目要求)
     if (!CheckAdmin(header.UserName, header.PassWord))
     {
         throw new Exception("无权使用此服务");
     }
     try
     {
         string         xmlPath   = Path.Combine(toPath, "App_Data\\XML");
         BaseConfigInfo oldConfig = BaseConfigs.Deserialize(Path.Combine(fromPath, "config\\db.config"));
         oldConfig.DBConnectionString = oldConfig.DBConnectionString.Replace("{$App}", fromPath);
         BaseConfigInfo newConfig = BaseConfigs.Deserialize(Path.Combine(toPath, "config\\db.config"));
         newConfig.DBConnectionString = newConfig.DBConnectionString.Replace("{$App}", toPath);
         DBMigrator.DoMigrate(xmlPath, oldConfig, newConfig, tables);
         return("0");
     }
     catch (Exception ex)
     {
         string source = "We7.CMS.Install-InstallWebService—CopyTableDataFromCloneSite";
         EventLogHelper.WriteToLog(source, ex);
         throw We7Helper.RaiseException("CopyTableDataFromCloneSite", ex.Message, "", ex.Source, We7Helper.FaultCode.Server);
     }
 }
Example #4
0
        public static void ExecuteSQLGroup(BaseConfigInfo bci, List <string> files)
        {
            string basepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Install\\SQL");
            string corepath = Path.Combine(basepath, "Core");

            foreach (string file in files)
            {
                ExecuteSQL(bci, Path.Combine(corepath, file));
            }
            DirectoryInfo di = new DirectoryInfo(basepath);

            DirectoryInfo[] dis = di.GetDirectories();
            foreach (DirectoryInfo info in dis)
            {
                if (info.Name.ToLower() != "core")
                {
                    string otherpath = Path.Combine(basepath, info.Name);
                    foreach (string file in files)
                    {
                        ExecuteSQL(bci, Path.Combine(otherpath, file));
                    }
                }
            }
        }
Example #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            We7MenuControl menu = new We7MenuControl();

            //检查
            if (menu.AllShowMemuItem.Count == 0)
            {
                lock (syncRoot)
                {
                    if (menu.AllShowMemuItem.Count == 0)
                    {
                        // 无Menu数据则进行SQL执行
                        BaseConfigInfo bci = BaseConfigs.GetBaseConfig();
                        if (bci.DBType != "" && bci.DBConnectionString != "")
                        {
                            Installer.ExcuteSQLGroup(bci);
                            ApplicationHelper.ResetApplication();
                        }
                    }
                }
            }
            Response.Write(menu.AllMenuHtml());
            Response.End();
        }
Example #6
0
        public static BaseConfigInfo GetBaseConfig()
        {
            BaseConfigInfo objBaseConfig = new BaseConfigInfo();
            XmlDocument    xmlDoc        = new XmlDocument();

            xmlDoc.Load(MainForm.configFilePath);
            XmlNode xnBaseConfig = xmlDoc.SelectSingleNode("/JyiConfig");

            #region Proxy
            List <Natsuhime.Proxy.ProxyInfo> list = Natsuhime.Proxy.ProxyUtility.GetProxyList_FromConfig(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ProxyList.dat"));
            List <ProxyInfo> objProxyList         = new List <ProxyInfo>();
            foreach (Natsuhime.Proxy.ProxyInfo info in list)
            {
                ProxyInfo pi = new ProxyInfo();
                pi.Name    = info.Name;
                pi.Address = info.Address;
                pi.Port    = info.Port;
                objProxyList.Add(pi);
            }
            //XmlNodeList xnlProxys = xnBaseConfig.SelectSingleNode("Proxy").ChildNodes;

            //List<ProxyInfo> objProxyList = new List<ProxyInfo>();
            //foreach (XmlNode xnf in xnlProxys)
            //{
            //    ProxyInfo objProxy = new ProxyInfo();
            //    XmlElement xe = (XmlElement)xnf;
            //    objProxy.Name = xnf.InnerText;
            //    objProxy.Address = xnf.Attributes["Address"].Value;
            //    objProxy.Port = int.Parse(xnf.Attributes["Port"].Value);
            //    objProxyList.Add(objProxy);
            //}
            objBaseConfig.ProxyList = objProxyList;
            #endregion

            return(objBaseConfig);
        }
Example #7
0
        private void ResetDBInfo_Click(object sender, EventArgs e)
        {
            CreateDataLogPath();

            if (GenerateConfigCheckbox.Checked)
            {
                string configPath = Server.MapPath("~/config/db.config");
                BaseConfigs.SaveConfigTo(DBConfig, configPath);
                BaseConfigs.ResetConfig();
            }

            //读取默认db.config文件内容
            BaseConfigInfo bci = BaseConfigs.GetBaseConfig();

            if (bci != null && bci.DBType != "" && bci.DBConnectionString != "")
            {
                Installer.ExcuteSQLGroup(bci);
                this.Response.Redirect("succeed.aspx");
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('无法读取数据库配置文件db.config,请检查重试。');</script>");
            }
        }
Example #8
0
        public void ExecuteProject()
        {
            m_MainForm.SetText(string.Format("项目『{0}』启动线程成功~\r\n", m_ProjectName));
            objPostProjectInfo = PostProjectConfig.GetConfig(m_ProjectName); //初始化项目实例
            objBaseConfigInfo  = BaseConfig.GetBaseConfig();                 //初始化基本配置类,目前代理列表在其中
            cookieContainer    = new CookieContainer();                      //初始化Cookie
            ProxyInfo objProxyInfo;                                          //声明代理信息对象
            WebProxy  objWebProxy = null;                                    //声明代理对象


            //需要使用的预处理参数列表
            List <ParmsInfo> objGetParmsInfoList = new List <ParmsInfo>();


            for (int i = 0; i < objPostProjectInfo.BaseInfo.Count; i++)
            {
                urlThreadSuccessFlag = 1;                                 //执行Url任务时候,如果为0,就跳出当前Url列表,重新开始新的列表.默认为成功(1,由于会在后面被重置为0,每个列表开始循环是先初始化为1,否则后面无法进行)
                if (objPostProjectInfo.BaseInfo.ClearCookieEverytime > 0) //如果每个周期循环前都需要清除Cookie
                {
                    cookieContainer = new CookieContainer();
                }

                if (objPostProjectInfo.BaseInfo.UseCookie <= 0)
                {
                    cookieContainer = null;//如果cookie为空,在conn类中将自动判断为不使用cookie
                }


                objWebProxy = null;//初始化代理对象为空(因为如果代理为空,在conn类中将自动判断为不使用代理.如果要使用代理,则通过下面的语句赋值)
                if (objPostProjectInfo.BaseInfo.UseProxy > 0)
                {
                    objProxyInfo = Proxy.GetNextProxy(objBaseConfigInfo.ProxyList); //获取未使用过的代理信息对象

                    if (objProxyInfo != null)                                       //如果配置为需要使用代理且代理没有循环完,则赋值给代理对象,但是代理却用完了,则终止
                    {
                        objWebProxy = new WebProxy(objProxyInfo.Address, objProxyInfo.Port);
                    }
                    else
                    {
                        m_MainForm.SetText("无可用代理,自动停止项目执行!\r\n");
                        Utility.Utility.WriteGoodProxyListToXml(objGoodProxyInfoList);//写入goodproxy
                        Thread.CurrentThread.Abort();
                    }
                }


                //开始处理Url列表并链接
                foreach (UrlInfo objUrlInfo in objPostProjectInfo.UrlInfoList)
                {
                    if (urlThreadSuccessFlag == 0)
                    {
                        m_MainForm.SetText(string.Format("\r\n===========在上个Url连接中失败,重新开始新一轮的列表循环===========\r\n"));
                        //continue;
                        break;
                    }
                    m_MainForm.SetText(string.Format("Url:[{0}]开始\r\n", objUrlInfo.Name));
                    for (int j = 0; j < objUrlInfo.Count; j++)//目前不管Count是多少还只能使用一个代理连接,想到的解决方案是,拷贝一份objProxyInfoList,然后再当前Url里面循环
                    {
                        if (objUrlInfo.Method == "POST")
                        {
                            StringBuilder sbParms = new StringBuilder();
                            foreach (ParmsInfo objPostParmsInfo in objUrlInfo.PostParmsList)//目前Url参数全部post,然后从objGetParmsList中得到预处理参数post
                            {
                                if (objPostParmsInfo.Type == "Rand")
                                {
                                    sbParms.Append(string.Format("&{0}={1}", objPostParmsInfo.Name, Utility.Utility.GenerateRandom(8, Jyi.Utility.Utility.RandomType.Lowercased)));
                                }
                                else if (objPostParmsInfo.Type == "RandEmail")
                                {
                                    sbParms.Append(string.Format("&{0}={1}@qq.com", objPostParmsInfo.Name, Utility.Utility.GenerateRandom(8)));
                                }
                                else if (objPostParmsInfo.Type == "VCode")
                                {
                                    #region 得到验证码
                                    HttpWebRequest objImgRequest = (HttpWebRequest)HttpWebRequest.Create(objUrlInfo.VCodeUrl);
                                    objImgRequest.Method          = "GET";
                                    objImgRequest.CookieContainer = cookieContainer;
                                    if (objWebProxy != null)
                                    {
                                        objImgRequest.Proxy = objWebProxy;
                                    }
                                    WebResponse          wr2    = objImgRequest.GetResponse();
                                    System.IO.Stream     s      = wr2.GetResponseStream();
                                    System.Drawing.Image numPic = System.Drawing.Image.FromStream(s);// 得到验证码图片

                                    UnCode objUnCode = new UnCode((System.Drawing.Bitmap)numPic);
                                    #endregion

                                    sbParms.Append(string.Format("&{0}={1}", objPostParmsInfo.Name, objUnCode.getPicnum(objUrlInfo.UnCodeList)));
                                }
                                else if (objPostParmsInfo.Type == "PreParm")
                                {
                                    foreach (ParmsInfo objGetParms in objGetParmsInfoList)
                                    {
                                        if (objPostParmsInfo.Name == objGetParms.Name)
                                        {
                                            sbParms.Append(string.Format("&{0}={1}", objPostParmsInfo.Name, objGetParms.Type));
                                            m_MainForm.SetText(string.Format("取得预处理参数:{0}={1}\r\n", objPostParmsInfo.Name, objGetParms.Type));
                                        }
                                    }
                                }
                                else
                                {
                                    sbParms.Append(string.Format("&{0}={1}", objPostParmsInfo.Name, objPostParmsInfo.Type));
                                }
                            }

                            //执行RemoveParms,移除本次使用后别人不再使用的预处理参数,避免在后面的Url的Post中遇到重名的参数被错误Post
                            if (objUrlInfo.RemoveParms != "")
                            {
                                int listCount = objGetParmsInfoList.Count;
                                //copy副本
                                //List<ParmsInfo> objGetParmsInfoListTemp = new List<ParmsInfo>() ;
                                //foreach (ParmsInfo objGetParmInfo in objGetParmsInfoList)
                                //{
                                //    ParmsInfo objCopyGetParmsInfo = new ParmsInfo();
                                //    objCopyGetParmsInfo.Name = objGetParmInfo.Name;
                                //    objCopyGetParmsInfo.Type = objGetParmInfo.Type;
                                //    objGetParmsInfoListTemp.Add(objCopyGetParmsInfo);
                                //}

                                foreach (string strRemoveParm in objUrlInfo.RemoveParms.Split(','))
                                {
                                    for (int k = 0; k < listCount; k++)
                                    {
                                        if (objGetParmsInfoList[k].Name == strRemoveParm)
                                        {
                                            objGetParmsInfoList.Remove(objGetParmsInfoList[k]);
                                            m_MainForm.SetText(string.Format("移除预处理参数{0}\r\n", strRemoveParm));
                                        }
                                    }
                                    //foreach (ParmsInfo objGetParms in objGetParmsInfoListTemp)
                                    //{
                                    //    if (objGetParms.Name == strRemoveParm)
                                    //    {
                                    //        objGetParmsInfoList.Remove(objGetParms);
                                    //        m_MainForm.SetText(string.Format("移除预处理参数{0}\r\n", objGetParms.Name));
                                    //    }
                                    //}
                                }
                            }
                            m_MainForm.SetText(string.Format("(POST){0}\r\n", objUrlInfo.Url));

                            //POST数据
                            string returnData = Conn.PostData(objUrlInfo.Url, objPostProjectInfo.BaseInfo.Charset, sbParms.ToString(), objUrlInfo.Referer, 0, objWebProxy, cookieContainer);

                            if (returnData.IndexOf("Jyi链接失败") >= 0)
                            {
                                m_MainForm.SetText("链接失败!\r\n");
                                m_MainForm.SetText(string.Format("===\r\n{0}\r\n===\r\n", returnData));
                                //Thread.CurrentThread.Abort();
                                urlThreadSuccessFlag = 0;
                                //continue;
                                break;
                            }
                            else if (returnData.IndexOf(objUrlInfo.SuccessText) >= 0)
                            {
                                m_MainForm.SetText("(POST)成功!\r\n");
                                urlThreadSuccessFlag = 1;
                            }
                            else
                            {
                                m_MainForm.SetText("(POST)失败!\r\n");
                                m_MainForm.SetText(string.Format("===\r\n{0}\r\n===\r\n", returnData));
                                //Thread.CurrentThread.Abort();
                                urlThreadSuccessFlag = 0;
                                //continue;
                                break;
                            }


                            //得到预处理参数,添加到预处理列表中
                            if (objUrlInfo.HaveGetParms > 0)
                            {
                                foreach (GetParmsInfo objGetParm in objUrlInfo.GetParmsList)
                                {
                                    ParmsInfo objAddGetParm = new ParmsInfo();
                                    objAddGetParm.Name = objGetParm.Name;
                                    RegexFunc rFunc = new RegexFunc();
                                    objAddGetParm.Type = System.Web.HttpUtility.UrlEncode(rFunc.GetMatch(returnData, objGetParm.Regex), Encoding.GetEncoding(objPostProjectInfo.BaseInfo.Charset));
                                    objGetParmsInfoList.Add(objAddGetParm);

                                    m_MainForm.SetText(string.Format("获取参数{0}的值为{1}\r\n", objAddGetParm.Name, objAddGetParm.Type));
                                }
                            }

                            m_MainForm.SetText(string.Format("(POST)结束\r\n"));

                            Thread.Sleep(objUrlInfo.WaitTime);//Url间隔时间
                        }
                        else
                        {
                            //TODO GETDATA TODAY



                            m_MainForm.SetText(string.Format("(GET){0}\r\n", objUrlInfo.Url));

                            //POST数据
                            string returnData = Conn.GetData(objUrlInfo.Url, objPostProjectInfo.BaseInfo.Charset, objUrlInfo.Referer, 0, objWebProxy, cookieContainer);

                            if (returnData.IndexOf("Jyi链接失败") >= 0)
                            {
                                m_MainForm.SetText("链接失败!\r\n");
                                m_MainForm.SetText(string.Format("===\r\n{0}\r\n===\r\n", returnData));
                                //Thread.CurrentThread.Abort();
                                urlThreadSuccessFlag = 0;
                                //continue;
                                break;
                            }
                            else if (returnData.IndexOf(objUrlInfo.SuccessText) >= 0)
                            {
                                m_MainForm.SetText("(GET)成功!\r\n");
                                urlThreadSuccessFlag = 1;
                            }
                            else
                            {
                                m_MainForm.SetText("(GET)失败!\r\n");
                                m_MainForm.SetText(string.Format("===\r\n{0}\r\n===\r\n", returnData));
                                //Thread.CurrentThread.Abort();
                                urlThreadSuccessFlag = 0;
                                //continue;
                                break;
                            }

                            if (objUrlInfo.HaveGetParms > 0)
                            {
                                //得到预处理参数,添加到预处理列表中
                                foreach (GetParmsInfo objGetParm in objUrlInfo.GetParmsList)
                                {
                                    ParmsInfo objAddGetParm = new ParmsInfo();
                                    objAddGetParm.Name = objGetParm.Name;
                                    RegexFunc rFunc = new RegexFunc();
                                    objAddGetParm.Type = System.Web.HttpUtility.UrlEncode(rFunc.GetMatch(returnData, objGetParm.Regex), Encoding.GetEncoding(objPostProjectInfo.BaseInfo.Charset));
                                    objGetParmsInfoList.Add(objAddGetParm);

                                    m_MainForm.SetText(string.Format("获取参数{0}的值为{1}\r\n", objAddGetParm.Name, objAddGetParm.Type));
                                }
                            }

                            m_MainForm.SetText(string.Format("(GET)结束\r\n"));

                            Thread.Sleep(objUrlInfo.WaitTime);//Url间隔时间
                        }
                    }
                    m_MainForm.SetText(string.Format("Url:[{0}]完毕\r\n", objUrlInfo.Name));
                }

                if (urlThreadSuccessFlag == 1 && objWebProxy != null)
                {
                    ProxyInfo objGoodProxyInfo = new ProxyInfo();
                    objGoodProxyInfo.Address = objWebProxy.Address.Host;
                    objGoodProxyInfo.Port    = objWebProxy.Address.Port;
                    objGoodProxyInfo.Name    = "GoodProxy";
                    objGoodProxyInfoList.Add(objGoodProxyInfo);
                }
                m_MainForm.SetText(string.Format("项目『{0}』线程完成一次循环~\r\n", m_ProjectName));
                Thread.Sleep(objPostProjectInfo.BaseInfo.WaitTime);//项目间隔时间
            }



            if (objWebProxy != null)
            {
                Utility.Utility.WriteGoodProxyListToXml(objGoodProxyInfoList);//写入goodproxy
            }
            m_MainForm.SetText(string.Format("项目『{0}』成功完成任务~\r\n", m_ProjectName));


            //TODO:处理点X关闭的时候自动结束线程,避免线程访问窗体出错
        }
Example #9
0
        public static int CreateDatabase(BaseConfigInfo bci, out Exception resultException)
        {
            int result = 0; //数据库新建失败

            resultException = null;
            DatabaseInfo dbi    = GetDatabaseInfo(bci);
            string       dbFile = "";

            if (dbi.DBFile != null && dbi.DBFile != "")
            {
                dbFile = dbi.DBFile.Replace("{$App}", AppDomain.CurrentDomain.BaseDirectory);
                dbFile.Replace('\\', Path.DirectorySeparatorChar);
            }

            try
            {
                switch (bci.DBType)
                {
                case "SqlServer":
                    string    masterstring = string.Format(@"Server={0};Database={1};User={2};Password={3};", dbi.Server, "master", dbi.User, dbi.Password);
                    string    sql          = string.Format(@"IF NOT EXISTS (SELECT * FROM SYSDATABASES WHERE NAME=N'{0}') CREATE DATABASE {0}", dbi.Database);
                    IDbDriver driver       = new SqlDbDriver();

                    using (IConnection conn = driver.CreateConnection(masterstring))
                    {
                        SqlStatement st0   = new SqlStatement(string.Format("SELECT count(*) FROM SYSDATABASES WHERE NAME=N'{0}'", dbi.Database));
                        int          count = (int)conn.QueryScalar(st0);
                        if (count == 0)
                        {
                            SqlStatement st = new SqlStatement(sql);
                            driver.FormatSQL(st);
                            driver.FormatSQL(st0);
                            conn.Update(st);
                            if ((int)conn.QueryScalar(st0) > 0)
                            {
                                result = 1;     //代表数据库新建成功
                            }
                        }
                        else
                        {
                            result = -1;        //代表数据库已经存在,无需新建
                        }
                    }
                    break;

                case "MySql":
                    result = -1;
                    break;

                case "Oracle":
                    result = -1;
                    break;

                case "SQLite":
                    if (File.Exists(dbFile))
                    {
                        result = -1;
                    }
                    else
                    {
                        string dbPath = Path.GetDirectoryName(dbFile);
                        if (!Directory.Exists(dbPath))
                        {
                            Directory.CreateDirectory(dbPath);
                        }
                        System.Data.SQLite.SQLiteConnection.CreateFile(dbFile);
                        if (File.Exists(dbFile))
                        {
                            result = 1;
                        }
                    }
                    break;

                case "Access":
                    if (File.Exists(dbFile))
                    {
                        result = -1;
                    }
                    else
                    {
                        string dbPath = Path.GetDirectoryName(dbFile);
                        if (!Directory.Exists(dbPath))
                        {
                            Directory.CreateDirectory(dbPath);
                        }
                        ADOX.Catalog catalog = new ADOX.Catalog();
                        catalog.Create(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5;", dbFile));
                        if (File.Exists(dbFile))
                        {
                            result = 1;
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                resultException = ex;
                result          = 0;
            }

            return(result);
        }
Example #10
0
        private void CopyFilesButton_Click(object sender, EventArgs e)
        {
            //configuration文件夹改名 兼容2.7以前版本方法
            string oldConfigPath = Path.Combine(Server.MapPath("~/"), "configuration");

            if (Directory.Exists(oldConfigPath))
            {
                string destDirName = Path.Combine(Server.MapPath("~/"), "config");
                if (Directory.Exists(destDirName))
                {
                    Directory.Delete(destDirName, true);
                }
                Directory.Move(oldConfigPath, Path.Combine(Server.MapPath("~/"), "config"));
            }

            if (BackUpPanel.Visible)
            {
                if (BackUpCheckBox.Checked)
                {
                    Installer.BackupOldFiles(Server.MapPath("~/"), Server.MapPath("~/_backup/update/"));
                }

                //检查是否有冗余文件
                if (ClearOldCheckBox.Visible && ClearOldCheckBox.Checked)
                {
                    //此处应该返回错误信息,目前存储在LOG文件中
                    DeleteFiles();
                }
            }

            string ext = Path.GetExtension(UploadFile);

            switch (ext.ToLower())
            {
            case ".zip":
                try
                {
                    //DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath("~/bin"));
                    //Helper.DeleteFileTree(directoryInfo, false);
                    We7Helper.CopyDirectory(UnZipPath, Server.MapPath("~/"));

                    Directory.Delete(UnZipPath, true);
                    //

                    /*
                     *
                     * 保存新版本号
                     * GeneralConfigInfo si = GeneralConfigs.GetConfig();
                     * if (si != null)
                     * {
                     *  //si.ProductVersion = NewVersion;
                     *  GeneralConfigs.SaveConfig(si);
                     * }
                     */
                    RegisterScript("alert('操作成功!');location.href='upgrade-db.aspx?from=upgrade.aspx'");
                }
                catch (IOException ex)
                {
                    RegisterScript("alert('文件复制失败。原因:" + ex.Message + "');");
                }
                break;

            case ".dll":
                try
                {
                    string targetfile = Path.Combine(Server.MapPath("~/bin/"), Path.GetFileName(UploadFile));
                    File.Copy(UploadFile, targetfile, true);
                    RegisterScript("alert('文件更新成功!');");
                }
                catch (IOException ex)
                {
                    RegisterScript("alert('文件复制失败。原因:" + ex.Message + "');");
                }
                break;

            case ".xml":
                try
                {
                    //读取默认db.config文件内容
                    BaseConfigInfo bci = BaseConfigs.GetBaseConfig();
                    if (bci != null && bci.DBType != "" && bci.DBConnectionString != "")
                    {
                        Installer.ExcuteSQL(bci, UploadFile);
                    }
                    RegisterScript("alert('XML文件执行成功!');");
                }
                catch (IOException ex)
                {
                    RegisterScript("alert(''XML文件执行出现错误。原因:" + ex.Message + "');");
                }
                break;
            }
        }
Example #11
0
        /// <summary>
        /// 重启网站
        /// </summary>
        public static void ResetApplication()
        {
            lock (lockHelper)
            {
                HttpContext context = HttpContext.Current;
                context.Application.Clear();

                if (context.Session != null)
                {
                    context.Session.Clear();
                }

                BaseConfigs.ResetConfig();
                SiteConfigs.ResetConfig();
                GeneralConfigs.ResetConfig();
                PluginManager.LoadPlugins();
                context.Application["We7.Application.OnlinePeople.Key"] = 0;

                //如果数据库配置文件存在,加载配置
                if (BaseConfigs.ConfigFileExist())
                {
                    BaseConfigInfo baseconfig = BaseConfigs.GetBaseConfig();

                    //加载数据库映射表
                    string          root     = context.Server.MapPath("~/");
                    string          dataPath = context.Server.MapPath("~/App_Data/XML");
                    ObjectAssistant assistat = new ObjectAssistant();
                    try
                    {
                        if (baseconfig != null && baseconfig.DBConnectionString != "")
                        {
                            baseconfig.DBConnectionString = baseconfig.DBConnectionString.
                                                            Replace("{$App}", AppDomain.CurrentDomain.BaseDirectory).Replace("\\\\", "\\");
                            assistat.LoadDBConnectionString(baseconfig.DBConnectionString, baseconfig.DBDriver);
                        }
                        assistat.LoadDataSource(dataPath);
                    }
                    catch (Thinkment.Data.DataException ex)
                    {
                        Debug.WriteLine(ex.ToString());
                        string source = "CD.Utils_CDHelper_ResetApplication";
                        EventLogHelper.WriteToLog(source, ex, EventLogEntryType.Error);

                        string msg = string.Format("注意检查:/app_data/xml里的配置文件:\r\n错误代码:{0}\r\n错误消息:{1}"
                                                   , ex.ErrorCode, ex.Message);
                        We7.Framework.LogHelper.WriteLog(typeof(ApplicationHelper), msg);
                        throw ex;
                    }

                    HelperFactory hf = new HelperFactory();

                    /*
                     * 添加内容模型表结构(系统内置字段已在LoadDataSource里添加)
                     * author:丁乐
                     */
                    ModelHelper.ReCreateModelIndex();
                    MoudelMonitoring.SetModelDataDic(assistat);

                    hf.Assistant = assistat;
                    hf.Root      = root;
                    hf.Initialize();
                    context.Application.Add("We7.HelperFactory", hf);
                    AppCtx.Cache.AddObject(HelperFactory.CacheKey, hf);

                    MoudelMonitoring ml = new MoudelMonitoring();  //监控内容模型
                }
            }
        }
Example #12
0
 public static void DoMigrate(string xmlPath, BaseConfigInfo oldConfig, BaseConfigInfo newConfig)
 {
     DoMigrate(xmlPath, oldConfig, newConfig, null);
 }
Example #13
0
        private void beginInstall()
        {
            /*
             * string dbname = this.TxtDBName.Text;
             * string dbuser = this.TxtDBUser.Text;
             * string dbpass = this.TxtDBPass.Text;
             * string dbserver = this.TxtDBService.Text;
             */

            dbserver = KSCMS.S("dbserver");
            dbuser   = KSCMS.S("dbuser");
            dbname   = KSCMS.S("dbname");
            dbpass   = KSCMS.S("dbpass");
            int fulldata = Utils.StrToInt(KSCMS.S("fulldata"));


            if (string.IsNullOrEmpty(dbname))
            {
                tips("请输入数据库名称!");
            }
            if (string.IsNullOrEmpty(dbserver))
            {
                tips("请输入服务器名称!");
            }

            string dbSqlPath = HttpContext.Current.Server.MapPath("~/install/DBStructure.sql");

            if (File.Exists(dbSqlPath))
            {
                connStr = string.Format("data source={0};user id={1};password={2};persist security info=false;", dbserver, dbuser, dbpass);

                try
                {
                    #region 创建数据库
                    ExecuteSql(connStr, "master", "IF Not EXISTS (select name from master.dbo.sysdatabases where name = N'" + dbname + "') CREATE DATABASE " + dbname + " COLLATE Chinese_PRC_CI_AS");
                    #endregion
                }
                catch (Exception ex)
                {
                    tips(ex.Message);
                }

                #region 运行创建表脚本

                doSql(connStr, dbname, dbSqlPath);                                            //创建结构

                if (fulldata == 1)                                                            //完整体验包
                {
                    dbSqlPath = HttpContext.Current.Server.MapPath("~/install/fulldata.sql"); //导入初始数据
                }
                else
                {
                    dbSqlPath = HttpContext.Current.Server.MapPath("~/install/basedata.sql");  //导入初始数据
                }
                doSql(connStr, dbname, dbSqlPath);



                #endregion



                BaseConfigInfo __configinfo = BaseConfigManage.Deserialize(Server.MapPath(KSCMS.GetInstallDir() + "conn.config"));
                __configinfo.SqlConnStr = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=true;", dbserver, dbuser, dbpass, dbname);
                BaseConfigManage.Serialiaze(__configinfo, Server.MapPath(KSCMS.GetInstallDir() + "conn.config"));



                tips("success");
            }
            else
            {
                tips("数据库脚本文件不存在!");
            }
        }
Example #14
0
        /// <summary>
        /// 获取真实基础配置对象
        /// </summary>
        /// <returns></returns>
        public static BaseConfigInfo GetRealBaseConfig()
        {
            BaseConfigInfo newBaseConfig = null;
            string         filename      = BaseConfigFileManager.ConfigFilePath;

            //string filename = null;
            //HttpContext context = HttpContext.Current;
            //if(context != null)
            //    filename = context.Server.MapPath("/DNT.config");
            //else
            //    filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,  "DNT.config");

            try
            {
                newBaseConfig = (BaseConfigInfo)SerializationHelper.Load(typeof(BaseConfigInfo), filename);
            }
            catch
            {
                newBaseConfig = null;
            }

            if (newBaseConfig == null)
            {
                try
                {
                    BaseConfigInfoCollection bcc = (BaseConfigInfoCollection)SerializationHelper.Load(typeof(BaseConfigInfoCollection), filename);
                    foreach (BaseConfigInfo bc in bcc)
                    {
                        if (Utils.GetTrueForumPath() == bc.Forumpath)
                        {
                            newBaseConfig = bc;
                            break;
                        }
                    }
                    if (newBaseConfig == null)
                    {
                        BaseConfigInfo rootConfig = null;
                        foreach (BaseConfigInfo bc in bcc)
                        {
                            if (Utils.GetTrueForumPath().StartsWith(bc.Forumpath) && bc.Forumpath != "/")
                            {
                                newBaseConfig = bc;
                                break;
                            }
                            if (("/").Equals(bc.Forumpath))
                            {
                                rootConfig = bc;
                            }
                        }
                        if (newBaseConfig == null)
                        {
                            newBaseConfig = rootConfig;
                        }
                    }
                }
                catch
                {
                    newBaseConfig = null;
                }
            }
            if (newBaseConfig == null)
            {
                throw new Exception("发生错误: 虚拟目录或网站根目录下没有正确的DNT.config文件,或者没有序列化权限");
            }
            return(newBaseConfig);
        }
Example #15
0
 static BaseConfigProvider()
 {
     config = GetRealBaseConfig();
 }
Example #16
0
        private static void SaveThumb(Image img, string newFileName, ImageFormat imgFormat, UpFileEntity upFileEntity)
        {
            BaseConfigInfo config   = BaseConfigs.GetConfig();
            string         fileName = Path.GetFileName(newFileName);

            if (config.DistributeFileSystem == 1 && upFileEntity.DistributeFileSystem == 1)
            {
                if (!string.IsNullOrEmpty(upFileEntity.GroupName))
                {
                    byte[] contentBytes = GetByteImage(img, imgFormat);
                    DFSProvider.CurrentDFS.UploadSlaveFile(contentBytes, upFileEntity.Mast_File_Name, upFileEntity.Prefix_Name, upFileEntity.File_Ext.Replace(".", ""));
                }
            }
            else
            {
                if (config.FTPEnable == 1 && upFileEntity.FTPEnable == 1)
                {
                    if (FTPs.IsLocalhost(upFileEntity.FTPIdent))//区分本地或FTP
                    {
                        img.Save(newFileName, imgFormat);
                    }
                    else
                    {
                        string fileExt = Path.GetExtension(newFileName);
                        string dir     = Path.GetDirectoryName(config.FTPTempPath + GetFtpPath("", fileExt, config.FTPPathFormat, upFileEntity));
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        string savePath = dir + "/" + fileName;
                        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
                        stopwatch.Start();
                        img.Save(savePath, imgFormat);                                                                      //存入临时文件夹
                        FTPs.UpLoadFile(Path.GetDirectoryName(newFileName), savePath, upFileEntity, upFileEntity.FTPIdent); //-FTP不需要传入文件名
                        stopwatch.Stop();
                        long minsecond = stopwatch.ElapsedMilliseconds;
                    }
                }
                else
                {
                    img.Save(newFileName, imgFormat);
                }
            }
            img.Dispose();
            #region 写入备份记录-通过接口
            if (upFileEntity.AttachID > 0)
            {
                fileName = fileName.ToLower().Replace(upFileEntity.File_Ext.ToLower(), "");
                string[] fileNameArr = fileName.Split('!');
                string[] sites;
                if (fileNameArr.Length > 1)
                {
                    sites = fileNameArr[1].Split('_');
                }
                else
                {
                    sites = fileName.Split('_');
                }
                if (sites.Length == 3)
                {
                    if (!string.IsNullOrEmpty(config.BakClassName))
                    {
                        UploadBakProvider.GetInstance(config.BakClassName).Update(upFileEntity.AttachID, sites[1] + "_" + sites[2]);
                    }
                }
            }
            #endregion
        }
Example #17
0
        /// <summary>
        /// 执行SQL,进行数据库初始化
        /// </summary>
        public static void ExcuteSQL(BaseConfigInfo bci, string updateFile)
        {
            if (updateFile != "")
            {
                string      connectionString = bci.DBConnectionString.Replace("{$App}", AppDomain.CurrentDomain.BaseDirectory);
                XmlDocument doc = new XmlDocument();
                doc.Load(updateFile);

                foreach (XmlNode node in doc.SelectNodes("/Update/Database"))
                {
                    IDbDriver dbDriver = CreateDbDriver(bci.DBType);
                    if (dbDriver == null)
                    {
                        continue;
                    }

                    //开始处理

                    int success = 0;
                    int errors  = 0;
                    using (IConnection conn = dbDriver.CreateConnection(connectionString))
                    {
                        foreach (XmlNode sub in node.SelectNodes("Sql"))
                        {
                            if (sub == null || String.IsNullOrEmpty(sub.InnerText) || String.IsNullOrEmpty(sub.InnerText.Trim()))
                            {
                                continue;
                            }
                            //不执行菜单操作
                            string menuop = sub.InnerText.Trim().ToLower();
                            if (menuop.StartsWith("insert") || menuop.StartsWith("delete") && menuop.Contains("menu"))
                            {
                                continue;
                            }

                            //读取SQL语句,逐一执行
                            SqlStatement sql = new SqlStatement();
                            sql.CommandType = System.Data.CommandType.Text;
                            sql.SqlClause   = sub.InnerText.Trim();
                            dbDriver.FormatSQL(sql);
                            try
                            {
                                conn.Update(sql);
                                success++;
                            }
                            catch (Exception ex)
                            {
                                //出现了错误,我们继续执行
                                We7.Framework.LogHelper.WriteFileLog(We7.Framework.LogHelper.sql_plugin_update,
                                                                     "执行SQL:" + sql.SqlClause, ex.Message);
                                errors++;
                                continue;
                            }
                        }
                    }


                    We7.Framework.LogHelper.WriteFileLog(We7.Framework.LogHelper.sql_plugin_update.ToString(),
                                                         "执行完毕:",
                                                         string.Format("{3}执行完毕!共执行语句{0}条,成功{1},失败{2} 。", success + errors, success, errors, updateFile));
                }
            }
        }
Example #18
0
 /// <summary>
 /// 重设配置类实例
 /// </summary>
 public static void ResetRealConfig()
 {
     m_configinfo = BaseConfigFileManager.LoadRealConfig();
 }
Example #19
0
        /// <summary>
        /// 重写Url
        /// </summary>
        /// <param name="sender">事件的源</param>
        /// <param name="e">包含事件数据的 EventArgs</param>
        private void ReUrl_BeginRequest(object sender, EventArgs e)
        {
            BaseConfigInfo baseconfig = new BaseConfigInfo();

            if (baseconfig == null)
            {
                return;
            }
            GeneralConfigInfo config    = GeneralConfigs.GetConfig();
            HttpContext       context   = ((HttpApplication)sender).Context;
            string            forumPath = (context.Request.ApplicationPath).ToLower();

            //if (context.Request.Url.AbsoluteUri.IndexOf("localhost") > 0 || context.Request.Url.AbsoluteUri.IndexOf("127.0.0.1") > 0)
            //{
            //    forumPath = forumPath + "/";
            //}

            forumPath = forumPath + "/";

            string requestPath = context.Request.Path.ToLower();

            if (requestPath.StartsWith(forumPath) && !requestPath.EndsWith(".axd"))
            {
                if (requestPath.Substring(forumPath.Length).IndexOf("/") == -1)
                {                    // 当前样式id
                    string strTemplateid = config.Templateid.ToString();
                    if (Utils.InArray(Utils.GetCookie(Utils.GetTemplateCookieName()), Templates.GetValidTemplateIDList()))
                    {
                        strTemplateid = Utils.GetCookie(Utils.GetTemplateCookieName());
                    }

                    if (requestPath.EndsWith("/index.aspx"))
                    {
                        if (config.Indexpage == 0)
                        {
                            if (config.BrowseCreateTemplate == 1)
                            {
                                CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, "forumindex.aspx", int.Parse(strTemplateid));
                            }
                            context.RewritePath(forumPath + "aspx/" + strTemplateid + "/forumindex.aspx");
                        }
                        else
                        {
                            if (config.BrowseCreateTemplate == 1)
                            {
                                CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, "website.aspx", int.Parse(strTemplateid));
                            }
                            context.RewritePath(forumPath + "aspx/" + strTemplateid + "/website.aspx");
                        }

                        return;
                    }


                    //当使用伪aspx, 如:showforum-1.aspx等.
                    if (config.Aspxrewrite == 1)
                    {
                        foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                        {
                            if (Regex.IsMatch(requestPath, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                            {
                                string newUrl = Regex.Replace(requestPath.Substring(context.Request.Path.LastIndexOf("/")), url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);
                                if (config.BrowseCreateTemplate == 1)
                                {
                                    CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, url.Page.Replace("/", ""), int.Parse(strTemplateid));
                                }
                                //通过参数设置指定模板
                                if (config.Specifytemplate > 0)
                                {
                                    strTemplateid = SelectTemplate(strTemplateid, url.Page, newUrl);
                                }
                                context.RewritePath(forumPath + "aspx/" + strTemplateid + url.Page, string.Empty, newUrl + "&selectedtemplateid=" + strTemplateid);

                                return;
                            }
                        }
                    }

                    if (config.BrowseCreateTemplate == 1)
                    {
                        if (requestPath.IndexOf("showtemplate.aspx") != -1)
                        {
                            CreateTemplate(forumPath,
                                           Templates.GetTemplateItem(DNTRequest.GetInt("templateid", 1)).Directory,
                                           config.Indexpage == 0 ? "forumindex.aspx" : "website.aspx",
                                           DNTRequest.GetInt("templateid", 1)); //当跳转模板页时,生成目标文件
                        }
                        CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, requestPath.Substring(context.Request.Path.LastIndexOf("/")).Replace("/", ""), int.Parse(strTemplateid));
                    }
                    //通过参数设置指定模板
                    if (config.Specifytemplate > 0)
                    {
                        strTemplateid = SelectTemplate(strTemplateid, requestPath, context.Request.QueryString.ToString());
                    }
                    context.RewritePath(forumPath + "aspx/" + strTemplateid + requestPath.Substring(context.Request.Path.LastIndexOf("/")), string.Empty, context.Request.QueryString.ToString() + "&selectedtemplateid=" + strTemplateid);
                }
                else if (requestPath.StartsWith(forumPath + "archiver/"))
                {
                    //当使用伪aspx, 如:showforum-1.aspx等.
                    if (config.Aspxrewrite == 1)
                    {
                        string path = requestPath.Substring(forumPath.Length + 8);
                        foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                        {
                            if (Regex.IsMatch(path, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                            {
                                string newUrl = Regex.Replace(path, url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);

                                context.RewritePath(forumPath + "archiver" + url.Page, string.Empty, newUrl);
                                return;
                            }
                        }
                    }
                    return;
                }
                else if (requestPath.StartsWith(forumPath + "tools/"))
                {
                    //当使用伪aspx, 如:showforum-1.aspx等.
                    if (config.Aspxrewrite == 1)
                    {
                        string path = requestPath.Substring(forumPath.Length + 5);
                        foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                        {
                            if (Regex.IsMatch(path, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                            {
                                string newUrl = Regex.Replace(path, url.Pattern, Utils.UrlDecode(url.QueryString), Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);

                                context.RewritePath(forumPath + "tools" + url.Page, string.Empty, newUrl);
                                return;
                            }
                        }
                    }
                    return;
                }
                else if (requestPath.StartsWith(forumPath + "upload/") || requestPath.StartsWith(forumPath + "space/upload/"))
                {
                    context.RewritePath(forumPath + "index.aspx");
                    return;
                }
            }
        }
Example #20
0
        /// <summary>
        /// 重写Url
        /// </summary>
        /// <param name="sender">事件的源</param>
        /// <param name="e">包含事件数据的 EventArgs</param>
        private void ReUrl_BeginRequest(object sender, EventArgs e)
        {
            BaseConfigInfo baseconfig = BaseConfigProvider.Instance();

            if (baseconfig == null)
            {
                return;
            }

            GeneralConfigInfo config    = GeneralConfigs.GetConfig();
            HttpContext       context   = ((HttpApplication)sender).Context;
            string            forumPath = baseconfig.Forumpath.ToLower();

            string requestPath = context.Request.Path.ToLower();

            //非论坛目录下的请求,非aspx页面和系统指定的目录不在重写范围
            if (!requestPath.StartsWith(forumPath) || !requestPath.EndsWith(".aspx") || IgnorePathContains(requestPath, forumPath))
            {
                return;
            }

            //判断是否是版块重写名称的请求
            if ((config.Iisurlrewrite == 1 || config.Aspxrewrite == 1) && requestPath.EndsWith("/list.aspx"))
            {
                requestPath = requestPath.StartsWith("/") ? requestPath : "/" + requestPath;
                // 当前模板样式id
                string strTemplateid = config.Templateid.ToString();
                if (Utils.InArray(Utils.GetCookie(Utils.GetTemplateCookieName()), Templates.GetValidTemplateIDList()))
                {
                    strTemplateid = Utils.GetCookie(Utils.GetTemplateCookieName());
                }

                string[] path = requestPath.Replace(forumPath, "/").Split('/');

                //当使用伪aspx, 如:/版块别名/1(分页)等.
                if (path.Length > 1 && !Utils.StrIsNullOrEmpty(path[1]))
                {
                    int fid = 0;
                    foreach (Discuz.Entity.ForumInfo forumInfo in Forums.GetForumList())
                    {
                        if (path[1].ToLower() == forumInfo.Rewritename.ToLower())
                        {
                            fid = forumInfo.Fid;
                            break;
                        }
                    }
                    if (fid > 0)
                    {
                        string newUrl = "forumid=" + fid;
                        //如果数组长度大于2,且path[2]是个数字,则证明它是合法的索引
                        if (path.Length > 2 && Utils.IsNumeric(path[2]))
                        {
                            newUrl += "&page=" + path[2];
                        }

                        //通过参数设置指定模板
                        if (config.Specifytemplate > 0)
                        {
                            strTemplateid = SelectTemplate(strTemplateid, "showforum.aspx", newUrl);
                        }
                        CreatePage("showforum.aspx", forumPath, TypeConverter.StrToInt(strTemplateid));

                        context.RewritePath(forumPath + "aspx/" + strTemplateid + "/showforum.aspx", string.Empty, newUrl + "&selectedtemplateid=" + strTemplateid);
                        return;
                    }
                    context.RewritePath(requestPath.Replace("list.aspx", string.Empty), string.Empty, string.Empty);
                    return;
                }
            }

            //如果去除了forumpath之后请求中没有目录符号“/”
            if (requestPath.Substring(forumPath.Length).IndexOf("/") == -1)
            {
                // 当前样式id
                string strTemplateid = config.Templateid.ToString();
                if (Utils.InArray(Utils.GetCookie(Utils.GetTemplateCookieName()), Templates.GetValidTemplateIDList()))
                {
                    strTemplateid = Utils.GetCookie(Utils.GetTemplateCookieName());
                }

                //如果请求首页
                if (requestPath.EndsWith("/index.aspx"))
                {
                    //确定index.aspx定位至论坛首页还是聚合首页
                    string target = config.Indexpage == 0 ? "forumindex.aspx" : "website.aspx";
                    CreatePage(target, forumPath, TypeConverter.StrToInt(strTemplateid));
                    context.RewritePath(forumPath + "aspx/" + strTemplateid + "/" + target);
                    return;
                }

                //当使用伪aspx, 如:showforum-1.aspx等.
                if (config.Aspxrewrite == 1)
                {
                    foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                    {
                        if (Regex.IsMatch(requestPath, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                        {
                            string newUrl = Regex.Replace(requestPath.Substring(context.Request.Path.LastIndexOf("/")), url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);
                            CreatePage(url.Page.Replace("/", ""), forumPath, TypeConverter.StrToInt(strTemplateid));
                            //通过参数设置指定模板
                            if (config.Specifytemplate > 0)
                            {
                                strTemplateid = SelectTemplate(strTemplateid, url.Page, newUrl);
                            }

                            string queryString = context.Request.QueryString.ToString();
                            context.RewritePath(forumPath + "aspx/" + strTemplateid + url.Page, string.Empty, newUrl + "&selectedtemplateid=" + strTemplateid +
                                                (queryString == "" ? "" : "&" + queryString));
                            return;
                        }
                    }
                }

                CreatePage(requestPath.Substring(context.Request.Path.LastIndexOf("/")).Replace("/", ""),
                           forumPath, TypeConverter.StrToInt(strTemplateid));

                //通过参数设置指定模板
                if (config.Specifytemplate > 0)
                {
                    strTemplateid = SelectTemplate(strTemplateid, requestPath, context.Request.QueryString.ToString());
                }
                context.RewritePath(forumPath + "aspx/" + strTemplateid + requestPath.Substring(context.Request.Path.LastIndexOf("/")), string.Empty, context.Request.QueryString.ToString() + "&selectedtemplateid=" + strTemplateid);
                return;
            }

            //如果开启了伪静态
            if (config.Aspxrewrite == 1)
            {
                //如果是简洁版页面的请求
                if (requestPath.StartsWith(forumPath + "archiver/"))
                {
                    string path = requestPath.Substring(forumPath.Length + 8);
                    foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                    {
                        if (Regex.IsMatch(path, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                        {
                            string newUrl = Regex.Replace(path, url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);
                            context.RewritePath(forumPath + "archiver" + url.Page, string.Empty, newUrl);
                            return;
                        }
                    }
                }

                //如果是请求tools目录的页面请求,如rss-1.aspx
                if (requestPath.StartsWith(forumPath + "tools/"))
                {
                    string path = requestPath.Substring(forumPath.Length + 5);
                    foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                    {
                        if (Regex.IsMatch(path, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                        {
                            string newUrl = Regex.Replace(path, url.Pattern, Utils.UrlDecode(url.QueryString), Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);
                            context.RewritePath(forumPath + "tools" + url.Page, string.Empty, newUrl);
                            return;
                        }
                    }
                }
            }

            //如果是请求upload目录下的aspx文件
            if (requestPath.StartsWith(forumPath + "upload/") || requestPath.StartsWith(forumPath + "space/upload/") || requestPath.StartsWith(forumPath + "avatars/upload/"))
            {
                context.RewritePath(forumPath + "index.aspx");
                return;
            }

            #region comment out

            ////使用版块
            //if (requestPath.IndexOf("/install/") < 0 && requestPath.IndexOf("/upgrade/") < 0 && (config.Iisurlrewrite == 1 || config.Aspxrewrite == 1) &&
            //    requestPath.EndsWith("/list.aspx") && requestPath.IndexOf("/archiver/") < 0 && requestPath.IndexOf("/admin/") < 0 && requestPath.IndexOf("/aspx/") < 0 &&
            //    requestPath.IndexOf("/tools/") < 0 && requestPath.IndexOf("/space/") < 0)
            //{
            //    requestPath = requestPath.StartsWith("/") ? requestPath : "/" + requestPath;
            //    // 当前样式id
            //    string strTemplateid = config.Templateid.ToString();
            //    if (Utils.InArray(Utils.GetCookie(Utils.GetTemplateCookieName()), Templates.GetValidTemplateIDList()))
            //    {
            //        strTemplateid = Utils.GetCookie(Utils.GetTemplateCookieName());
            //    }

            //    string[] path = requestPath.Replace(BaseConfigs.GetForumPath, "/").Split('/');

            //    //当使用伪aspx, 如:/版块别名/1(分页)等.
            //    if (path.Length > 1 && !Utils.StrIsNullOrEmpty(path[1]))
            //    {
            //        int forumid = 0;
            //        foreach (Discuz.Entity.ForumInfo foruminfo in Forums.GetForumList())
            //        {
            //            if (path[1].ToLower() == foruminfo.Rewritename.ToLower())
            //            {
            //                forumid = foruminfo.Fid;
            //                break;
            //            }
            //        }
            //        if (forumid > 0)
            //        {
            //            string newUrl = "forumid=" + forumid;
            //            if (path.Length > 2 && !Utils.StrIsNullOrEmpty(path[2]) && path[2] != "list.aspx")
            //            {
            //                newUrl += "&page=" + path[2];
            //            }

            //            //通过参数设置指定模板
            //            if (config.Specifytemplate > 0)
            //            {
            //                strTemplateid = SelectTemplate(strTemplateid, "showforum.aspx", newUrl);
            //            }
            //            context.RewritePath(forumPath + "aspx/" + strTemplateid + "/showforum.aspx", string.Empty, newUrl + "&selectedtemplateid=" + strTemplateid);
            //            return;
            //        }
            //    }
            //    context.Response.Redirect(baseconfig.Forumpath + "tools/error.htm?forumpath=" + BaseConfigs.GetForumPath + "&templatepath=" + Templates.GetTemplateItem(Utils.StrToInt(strTemplateid, 0)).Directory + "&msg=" + Utils.UrlEncode("您请求的版块信息无效!"));
            //    return;
            //}
            //if (requestPath.StartsWith(forumPath))
            //{
            //    if (requestPath.Substring(forumPath.Length).IndexOf("/") == -1)
            //    {
            //        // 当前样式id
            //        string strTemplateid = config.Templateid.ToString();
            //        if (Utils.InArray(Utils.GetCookie(Utils.GetTemplateCookieName()), Templates.GetValidTemplateIDList()))
            //        {
            //            strTemplateid = Utils.GetCookie(Utils.GetTemplateCookieName());
            //        }

            //        if (requestPath.EndsWith("/index.aspx"))
            //        {
            //            if (config.Indexpage == 0)
            //            {
            //                if (config.BrowseCreateTemplate == 1)
            //                {
            //                    CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, "forumindex.aspx", int.Parse(strTemplateid));
            //                }
            //                context.RewritePath(forumPath + "aspx/" + strTemplateid + "/forumindex.aspx");
            //            }
            //            else
            //            {
            //                if (config.BrowseCreateTemplate == 1)
            //                {
            //                    CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, "website.aspx", int.Parse(strTemplateid));
            //                }
            //                context.RewritePath(forumPath + "aspx/" + strTemplateid + "/website.aspx");
            //            }

            //            return;
            //        }


            //        //当使用伪aspx, 如:showforum-1.aspx等.
            //        if (config.Aspxrewrite == 1)
            //        {
            //            foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
            //            {
            //                if (Regex.IsMatch(requestPath, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
            //                {
            //                    string newUrl = Regex.Replace(requestPath.Substring(context.Request.Path.LastIndexOf("/")), url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);
            //                    if (config.BrowseCreateTemplate == 1)
            //                    {
            //                        CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, url.Page.Replace("/", ""), int.Parse(strTemplateid));
            //                    }
            //                    //通过参数设置指定模板
            //                    if (config.Specifytemplate > 0)
            //                    {
            //                        strTemplateid = SelectTemplate(strTemplateid, url.Page, newUrl);
            //                    }
            //                    string queryString = context.Request.QueryString.ToString();
            //                    context.RewritePath(forumPath + "aspx/" + strTemplateid + url.Page, string.Empty, newUrl + "&selectedtemplateid=" + strTemplateid +
            //                        (queryString == "" ? "" : "&" + queryString));

            //                    return;
            //                }
            //            }
            //        }

            //        if (config.BrowseCreateTemplate == 1)
            //        {
            //            if (requestPath.IndexOf("showtemplate.aspx") != -1)
            //            {
            //                CreateTemplate(forumPath,
            //                    Templates.GetTemplateItem(DNTRequest.GetInt("templateid", 1)).Directory,
            //                    config.Indexpage == 0 ? "forumindex.aspx" : "website.aspx",
            //                    DNTRequest.GetInt("templateid", 1)); //当跳转模板页时,生成目标文件
            //            }
            //            CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, requestPath.Substring(context.Request.Path.LastIndexOf("/")).Replace("/", ""), int.Parse(strTemplateid));

            //        }

            //        //通过参数设置指定模板
            //        if (config.Specifytemplate > 0)
            //        {
            //            strTemplateid = SelectTemplate(strTemplateid, requestPath, context.Request.QueryString.ToString());
            //        }
            //        context.RewritePath(forumPath + "aspx/" + strTemplateid + requestPath.Substring(context.Request.Path.LastIndexOf("/")), string.Empty, context.Request.QueryString.ToString() + "&selectedtemplateid=" + strTemplateid);
            //    }

            //    else if (requestPath.StartsWith(forumPath + "archiver/"))
            //    {
            //        //当使用伪aspx, 如:showforum-1.aspx等.
            //        if (config.Aspxrewrite == 1)
            //        {
            //            string path = requestPath.Substring(forumPath.Length + 8);
            //            foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
            //            {
            //                if (Regex.IsMatch(path, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
            //                {
            //                    string newUrl = Regex.Replace(path, url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);

            //                    context.RewritePath(forumPath + "archiver" + url.Page, string.Empty, newUrl);
            //                    return;
            //                }
            //            }

            //        }
            //        return;
            //    }
            //    else if (requestPath.StartsWith(forumPath + "tools/"))
            //    {
            //        //当使用伪aspx, 如:showforum-1.aspx等.
            //        if (config.Aspxrewrite == 1)
            //        {
            //            string path = requestPath.Substring(forumPath.Length + 5);
            //            foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
            //            {
            //                if (Regex.IsMatch(path, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
            //                {
            //                    string newUrl = Regex.Replace(path, url.Pattern, Utils.UrlDecode(url.QueryString), Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);

            //                    context.RewritePath(forumPath + "tools" + url.Page, string.Empty, newUrl);
            //                    return;
            //                }
            //            }
            //        }
            //        return;
            //    }
            //    else if (requestPath.StartsWith(forumPath + "upload/") || requestPath.StartsWith(forumPath + "space/upload/") || requestPath.StartsWith(forumPath + "avatars/upload/"))
            //    {
            //        context.RewritePath(forumPath + "index.aspx");
            //        return;
            //    }

            //}

            #endregion
        }
Example #21
0
		/// <summary>
		/// 设置对象实例
		/// </summary>
		/// <param name="anConfig"></param>
		public static void SetInstance(BaseConfigInfo anConfig)
		{
			if (anConfig == null)
				return;
			config = anConfig;
		}
Example #22
0
        protected void ResetDBInfo_Click(object sender, EventArgs e)
        {
            #region 验证输入
            //验证密码长度
            if (AdminPasswordTextBox.Text.Length < 6)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('系统管理员密码长度不能少于6位');</script>");
                return;
            }
            //验证数据库名为空
            if (DatabaseTextBox.Text.Length == 0 && DbTypeDropDownList.SelectedValue == "SqlServer")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('数据库名不能为空');</script>");
                return;
            }

            //验证必须选择数据库类型
            if (DbTypeDropDownList.SelectedIndex == 0)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择数据库类型');</script>");
                return;
            }

            #endregion

            #region 写Site.config文件
            try
            {
                SiteConfigInfo __configinfo;
                //记录存储到SiteConfig.config
                try
                {
                    __configinfo = SiteConfigs.GetConfig();
                }
                catch
                {
                    __configinfo = new SiteConfigInfo();
                }
                __configinfo.AdministratorKey  = Encrypt(AdminPasswordTextBox.Text);
                __configinfo.IsPasswordHashed  = true;
                __configinfo.SiteName          = WebsiteNameTextBox.Text;
                __configinfo.AdministratorName = AdminNameTextBox.Text;
                SiteConfigs.Serialiaze(__configinfo, Server.MapPath("~/config/site.config"));
                Session["SystemAdminName"] = AdminNameTextBox.Text;
                Session["SystemAdminPws"]  = AdminPasswordTextBox.Text;
            }
            catch {; }
            #endregion

            string setupDbType = SelectDB = DbTypeDropDownList.SelectedValue;

            DatabaseInfo dbi = new DatabaseInfo();
            dbi.Server   = ServerTextBox.Text;
            dbi.Database = DatabaseTextBox.Text;
            dbi.User     = UserTextBox.Text;
            dbi.Password = PasswordTextBox.Text;
            dbi.DBFile   = DbFileNameTextBox.Text;

            BaseConfigInfo baseConfig = Installer.GenerateConnectionString(setupDbType, dbi);

            //验证链接

            if (!SaveDBConfig(baseConfig))
            {
                ResetDBInfo.Enabled = false;
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>if(confirm('无法把设置写入\"db.config\"文件, 系统将把文件内容显示出来, 您可以将内容保存为\"db.config\", 然后通过FTP软件上传到网站根目录下.. \\r\\n*注意: db.config位于网站Config目录。\\r\\n\\r\\n如果要继续运行安装, 请点击\"确定\"按钮. ')) {window.location.href='step4.aspx?isforceload=1';}else{window.location.href='step3.aspx';}</script>");
                return;
            }

            //下面数据库需要手工创建
            if (baseConfig.DBType == "Oracle" || baseConfig.DBType == "MySql")
            {
                CreateNewDBCheckBox.Checked = false;
            }

            if (CreateNewDBCheckBox.Checked)//创建数据库
            {
                Exception ex  = null;
                int       ret = Installer.CreateDatabase(baseConfig, out ex);
                if (ret == -1)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('数据库已存在,请重新命名或去掉重新“创建新数据库”前面的勾,使用已有数据库。');</script>");
                    return;
                }
                else if (ret == 0)
                {
                    string exceptionMsgs = We7Helper.ConvertTextToHtml(ex.Message);
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('创建数据库发生错误。错误原因:" + exceptionMsgs + "');</script>");
                    return;
                }
            }

            string msg = "";
            if (!Installer.CheckConnection(baseConfig, out msg))
            {
                msg = We7Helper.ConvertTextToHtml(msg);
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('连接数据库失败,请检查您填写的数据库信息。" + msg + "');</script>");
                return;
            }
            else
            {
                Response.Redirect(Server.HtmlEncode(String.Format("step4.aspx?db={0}", setupDbType)));
            }
        }
Example #23
0
        /// <summary>
        /// 重写Url
        /// </summary>
        /// <param name="sender">事件的源</param>
        /// <param name="e">包含事件数据的 EventArgs</param>
        private void ReUrl_BeginRequest(object sender, EventArgs e)
        {
            BaseConfigInfo baseconfig = BaseConfigProvider.Instance();

            if (baseconfig == null)
            {
                return;
            }
            GeneralConfigInfo config       = GeneralConfigs.GetConfig();
            HttpContext       context      = ((HttpApplication)sender).Context;
            string            sysPath      = baseconfig.Syspath.ToLower();
            string            requestValue = context.Request.QueryString.ToString();
            string            requestPath  = context.Request.Path.ToString();
            // 当前样式
            string strTemplateid = "1";

            if (requestPath.ToLower().StartsWith(sysPath))
            {
                if (requestPath.ToLower().Substring(sysPath.Length).IndexOf("/") == -1)
                {
                    if (requestPath.ToLower().EndsWith("/default.aspx"))
                    {
                        CreateTemplate(sysPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, "IndexPage.aspx", int.Parse(strTemplateid));

                        context.RewritePath(sysPath + "aspx/" + strTemplateid + "/IndexPage.aspx");

                        return;
                    }

                    //当使用伪aspx, 如:user-1.aspx等.
                    if (config.Aspxrewrite == 1)
                    {
                        foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                        {
                            if (Regex.IsMatch(requestPath, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                            {
                                string newUrl = Regex.Replace(requestPath.Substring(context.Request.Path.LastIndexOf("/")), url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);

                                //if ( url.Page.ToLower() =="/topapirecall.aspx")//淘宝回调处理
                                // {
                                //     context.RewritePath(sysPath + "Services/" + url.Page, string.Empty, newUrl + "&" + requestValue);
                                // }
                                // else
                                // {
                                context.RewritePath(sysPath + "aspx/" + strTemplateid + url.Page, string.Empty, newUrl + "&selectedtemplateid=" + strTemplateid + "&" + requestValue);
                                // }

                                return;
                            }
                        }
                    }

                    context.RewritePath(sysPath + "aspx/" + strTemplateid + requestPath.Substring(context.Request.Path.LastIndexOf("/")), string.Empty, context.Request.QueryString.ToString() + "&selectedtemplateid=" + strTemplateid);

                    return;
                }
                else if (requestPath.ToLower().StartsWith(sysPath + "home") || requestPath.ToLower().StartsWith(sysPath + "userheadimgu"))
                {
                    //当使用伪aspx, 如:user-1.aspx等.
                    if (config.Aspxrewrite == 1)
                    {
                        foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                        {
                            if (Regex.IsMatch(requestPath, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                            {
                                string newUrl = Regex.Replace(requestPath.Substring(context.Request.Path.LastIndexOf("/")), url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);

                                context.RewritePath(sysPath + "aspx/" + strTemplateid + url.Page, string.Empty, newUrl + "&selectedtemplateid=" + strTemplateid + "&" + requestValue);

                                return;
                            }
                        }
                    }
                    return;
                }

/*
 *              else if (requestPath.StartsWith(sysPath + "archiver/"))
 *              {
 *                  //当使用伪aspx
 *                  if (config.Aspxrewrite == 1)
 *                  {
 *                      string path = requestPath.Substring(sysPath.Length + 8);
 *                      foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
 *                      {
 *                          if (Regex.IsMatch(path, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
 *                          {
 *                              string newUrl = Regex.Replace(path, url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);
 *
 *                              context.RewritePath(sysPath + "archiver" + url.Page, string.Empty, newUrl);
 *                              return;
 *                          }
 *                      }
 *
 *                  }
 *                  return;
 *              }
 *              else if (requestPath.StartsWith(sysPath + "tools/"))
 *              {
 *                  //当使用伪aspx
 *                  if (config.Aspxrewrite == 1)
 *                  {
 *                      string path = requestPath.Substring(sysPath.Length + 5);
 *                      foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
 *                      {
 *                          if (Regex.IsMatch(path, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
 *                          {
 *                              string newUrl = Regex.Replace(path, url.Pattern, Utils.UrlDecode(url.QueryString), Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);
 *
 *                              context.RewritePath(sysPath + "tools" + url.Page, string.Empty, newUrl);
 *                              return;
 *                          }
 *                      }
 *                  }
 *                  return;
 *              }
 */
            }
        }
Example #24
0
        /// <summary>
        /// 重设BaseConfig
        /// </summary>
        /// <returns></returns>
        public static bool EditDntConfig()
        {
            BaseConfigInfo config   = null;
            string         filename = Discuz.Config.DefaultConfigFileManager.ConfigFilePath;//Utils.GetMapPath("/DNT.config");

            try
            {
                config = (BaseConfigInfo)SerializationHelper.Load(typeof(BaseConfigInfo), filename);
            }
            catch
            {
                config = null;
            }
            try
            {
                if (config != null)
                {
                    BaseConfigProvider.SetInstance(config);
                    return(true);
                }
            }
            catch
            {
                ;
            }
            if (config == null)
            {
                try
                {
                    BaseConfigInfoCollection bcc = (BaseConfigInfoCollection)SerializationHelper.Load(typeof(BaseConfigInfoCollection), filename);
                    foreach (BaseConfigInfo bc in bcc)
                    {
                        if (Utils.GetTrueForumPath() == bc.Forumpath)
                        {
                            config = bc;
                            break;
                        }
                    }

                    if (config == null)
                    {
                        foreach (BaseConfigInfo bc in bcc)
                        {
                            if (Utils.GetTrueForumPath().StartsWith(bc.Forumpath))
                            {
                                config = bc;
                                break;
                            }
                        }
                    }

                    if (config != null)
                    {
                        BaseConfigProvider.SetInstance(config);
                        return(true);
                    }
                }
                catch
                {
                    ;
                }
            }
            return(false);
        }
Example #25
0
        protected void ResetDBInfo_Click(object sender, EventArgs e)
        {
            if (AdminPasswordTextBox.Text.Length < 6)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('系统管理员密码不能少于6位!');</script>");
                return;
            }
            if (DatabaseTextBox.Text.Length == 0 && DBTypeDropDownList.SelectedValue == "SqlServer")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>数据库名称不能为空!</script>");
                return;
            }
            if (DBTypeDropDownList.SelectedIndex == 0)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择数据库类型!');</script>");
                return;
            }

            try
            {
                SiteConfigInfo __configinfo;
                try
                {
                    __configinfo = SiteConfigs.GetConfig();
                }
                catch
                {
                    __configinfo = new SiteConfigInfo();
                }
                __configinfo.AdministratorKey  = Encrypt(AdminPasswordTextBox.Text);
                __configinfo.IsPasswordHashed  = true;
                __configinfo.SiteName          = WebsiteNameTextBox.Text;
                __configinfo.AdministratorName = AdminNameTextBox.Text;
                SiteConfigs.Serialize(__configinfo, Server.MapPath("~/Config/site.config"));
                Session["SystemAdminName"] = AdminNameTextBox.Text;
                Session["SystemAdminPwd"]  = AdminPasswordTextBox.Text;
            }
            catch
            { }

            string       setupDBType = SelectDB = DBTypeDropDownList.SelectedValue;
            DatabaseInfo dbi         = new DatabaseInfo();

            dbi.Server   = ServerTextBox.Text;
            dbi.Database = DatabaseTextBox.Text;
            dbi.User     = UserTextBox.Text;
            dbi.Password = PasswordTextBox.Text;
            dbi.DBFile   = DBFileNameTextBox.Text;

            BaseConfigInfo bci = Installer.GenerateConnectionString(setupDBType, dbi);

            if (!SaveDBConfig(bci))
            {
                ResetDBInfo.Enabled = false;
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>if(confirm('无法把设置写入\"db.config\"文件,系统将把文件内容显示出来,您可以将内容保存为\"db.config\",然后通过FTP软件上传到网站根目录下.. \\r\\n*注意:db.config位于网站Config目录下。\\r\\n\\r\\n如要继续运行安装,请按\"确定\"按钮.')){window.location.href='step4.aspx?isforceload=1';}else{window.location.href='step3.aspx';}</script>");
                return;
            }

            if (bci.DBType == "Oracle" || bci.DBType == "MySql")
            {
                CreateNewDBCheckBox.Checked = false;
            }

            if (CreateNewDBCheckBox.Checked)
            {
                Exception ex  = null;
                int       ret = Installer.CreateDatabase(bci, out ex);

                if (ret == -1)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('数据库已经存在,请重新命名或去掉“创建新数据库”前的勾,使用已有数据库');</script>");
                    return;
                }
                if (ret == 0)
                {
                    string exceptionMsgs = We7Helper.ConvertTextToHtml(ex.Message);
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('数据库创建失败,错误原因:" + exceptionMsgs + "');</script>");
                    return;
                }
            }

            string msg = "";

            if (!Installer.CheckConnection(bci, out msg))
            {
                msg = We7Helper.ConvertTextToHtml(msg);
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('连接数据库失败,请检查您填写的数据库信息。" + msg + "');</script>");
                return;
            }
            else
            {
                Response.Redirect(Server.HtmlEncode(string.Format("step4.aspx?db={0}", setupDBType)), true);
            }
        }
Example #26
0
 /// <summary>
 /// 保存基础信息配置
 /// </summary>
 /// <param name="configInfo">基础信息</param>
 /// <returns>是否保存结果</returns>
 public bool SaveBaseConfig(BaseConfigInfo configInfo)
 {
     return(SaveConfigInfo(configInfo, IOHelper.GetMapPath(_baseconfigfilepath)));
 }
Example #27
0
        [SoapHeader("header")] //用户身份验证的soap header
        public string InitDBConfig(string setupDbType, DatabaseInfo dbi)
        {
            //验证是否有权访问(当然,也可以通过查询数据库实现,具体视项目要求)
            if (!CheckAdmin(header.UserName, header.PassWord))
            {
                throw new Exception("无权使用此服务");
            }

            string source = "We7.CMS.Install-InstallWebService-SetSiteConfig";

            try
            {
                BaseConfigInfo baseConfig = Installer.GenerateConnectionString(setupDbType, dbi);
                string         file       = Server.MapPath("~/config/db.config");
                BaseConfigs.SaveConfigTo(baseConfig, file);
                BaseConfigs.ResetConfig();
                if (dbi.CreateDB)
                {
                    Exception ex  = null;
                    int       ret = Installer.CreateDatabase(baseConfig, out ex);
                    if (ret == -1)
                    {
                        string    msg = "数据库已存在,请重新命名或去掉重新“创建新数据库”前面的勾,使用已有数据库。";
                        Exception ex1 = new Exception(msg);
                        EventLogHelper.WriteToLog(source, ex1, EventLogEntryType.Error);
                        return(msg);
                    }
                    else if (ret == 0)
                    {
                        string exceptionMsgs = ex.Message;
                        EventLogHelper.WriteToLog(source, ex, EventLogEntryType.Error);
                        return("创建数据库发生错误。错误原因:" + exceptionMsgs);
                    }
                }


                //设置数据库脚本路径
                //string basePath = Server.MapPath("/install/SQL");
                //if (!Directory.Exists(basePath))
                //{
                //    basePath = Server.MapPath("../install/SQL");
                //}


                if (!Directory.Exists(Server.MapPath("/_data/")))
                {
                    Directory.CreateDirectory(Server.MapPath("/_data/"));
                }


                List <string> files = new List <string>();
                files.Add("create.xml");
                files.Add("install.xml");
                files.Add("update.xml");
                Installer.ExcuteSQLGroup(baseConfig, files);

                //创建内容模型表
                Installer.CreateModelTables();
                ApplicationHelper.ResetApplication();

                return("0");
            }
            catch (Exception ex)
            {
                EventLogHelper.WriteToLog(source, ex, EventLogEntryType.Error);
                return("创建数据库发生错误。错误原因:" + ex.Message);
            }
        }
Example #28
0
        /// <summary>
        /// 重写Url
        /// </summary>
        /// <param name="sender">事件的源</param>
        /// <param name="e">包含事件数据的 EventArgs</param>
        private void ReUrl_BeginRequest(object sender, EventArgs e)
        {
            BaseConfigInfo baseconfig = BaseConfigProvider.Instance();

            if (baseconfig == null)
            {
                return;
            }

            GeneralConfigInfo config    = GeneralConfigs.GetConfig();
            HttpContext       context   = ((HttpApplication)sender).Context;
            string            forumPath = baseconfig.Forumpath.ToLower();

            string requestPath = context.Request.Path.ToLower();

            //使用版块
            if ((config.Iisurlrewrite == 1 || config.Aspxrewrite == 1) && requestPath.EndsWith("/list.aspx") &&
                requestPath.IndexOf("/archiver/") < 0 && requestPath.IndexOf("/install/") < 0 && requestPath.IndexOf("/upgrade/") < 0 &&
                requestPath.IndexOf("/admin/") < 0 && requestPath.IndexOf("/aspx/") < 0 && requestPath.IndexOf("/tools/") < 0 &&
                requestPath.IndexOf("/space/") < 0)
            {
                requestPath = requestPath.StartsWith("/") ? requestPath : "/" + requestPath;
                // 当前样式id
                string strTemplateid = config.Templateid.ToString();
                if (Utils.InArray(Utils.GetCookie(Utils.GetTemplateCookieName()), Templates.GetValidTemplateIDList()))
                {
                    strTemplateid = Utils.GetCookie(Utils.GetTemplateCookieName());
                }

                string[] path = requestPath.Replace(BaseConfigs.GetForumPath, "/").Split('/');

                //当使用伪aspx, 如:/版块别名/1(分页)等.
                if (path.Length > 1 && !Utils.StrIsNullOrEmpty(path[1]))
                {
                    int forumid = 0;
                    foreach (Discuz.Entity.ForumInfo foruminfo in Forums.GetForumList())
                    {
                        if (path[1].ToLower() == foruminfo.Rewritename.ToLower())
                        {
                            forumid = foruminfo.Fid;
                            break;
                        }
                    }
                    if (forumid > 0)
                    {
                        string newUrl = "forumid=" + forumid;
                        if (path.Length > 2 && !Utils.StrIsNullOrEmpty(path[2]) && path[2] != "list.aspx")
                        {
                            newUrl += "&page=" + path[2];
                        }

                        //通过参数设置指定模板
                        if (config.Specifytemplate > 0)
                        {
                            strTemplateid = SelectTemplate(strTemplateid, "showforum.aspx", newUrl);
                        }
                        context.RewritePath(forumPath + "aspx/" + strTemplateid + "/showforum.aspx", string.Empty, newUrl + "&selectedtemplateid=" + strTemplateid);
                        return;
                    }
                }
                context.Response.Redirect(baseconfig.Forumpath + "tools/error.htm?forumpath=" + BaseConfigs.GetForumPath + "&templatepath=" + Templates.GetTemplateItem(Utils.StrToInt(strTemplateid, 0)).Directory + "&msg=" + Utils.UrlEncode("您请求的版块信息无效!"));
                return;
            }

            if (requestPath.StartsWith(forumPath))
            {
                if (requestPath.Substring(forumPath.Length).IndexOf("/") == -1)
                {
                    // 当前样式id
                    string strTemplateid = config.Templateid.ToString();
                    if (Utils.InArray(Utils.GetCookie(Utils.GetTemplateCookieName()), Templates.GetValidTemplateIDList()))
                    {
                        strTemplateid = Utils.GetCookie(Utils.GetTemplateCookieName());
                    }

                    if (requestPath.EndsWith("/index.aspx"))
                    {
                        if (config.Indexpage == 0)
                        {
                            if (config.BrowseCreateTemplate == 1)
                            {
                                CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, "forumindex.aspx", int.Parse(strTemplateid));
                            }
                            context.RewritePath(forumPath + "aspx/" + strTemplateid + "/forumindex.aspx");
                        }
                        else
                        {
                            if (config.BrowseCreateTemplate == 1)
                            {
                                CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, "website.aspx", int.Parse(strTemplateid));
                            }
                            context.RewritePath(forumPath + "aspx/" + strTemplateid + "/website.aspx");
                        }

                        return;
                    }


                    //当使用伪aspx, 如:showforum-1.aspx等.
                    if (config.Aspxrewrite == 1)
                    {
                        foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                        {
                            if (Regex.IsMatch(requestPath, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                            {
                                string newUrl = Regex.Replace(requestPath.Substring(context.Request.Path.LastIndexOf("/")), url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);
                                if (config.BrowseCreateTemplate == 1)
                                {
                                    CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, url.Page.Replace("/", ""), int.Parse(strTemplateid));
                                }
                                //通过参数设置指定模板
                                if (config.Specifytemplate > 0)
                                {
                                    strTemplateid = SelectTemplate(strTemplateid, url.Page, newUrl);
                                }
                                context.RewritePath(forumPath + "aspx/" + strTemplateid + url.Page, string.Empty, newUrl + "&selectedtemplateid=" + strTemplateid);

                                return;
                            }
                        }
                    }

                    if (config.BrowseCreateTemplate == 1)
                    {
                        if (requestPath.IndexOf("showtemplate.aspx") != -1)
                        {
                            CreateTemplate(forumPath,
                                           Templates.GetTemplateItem(DNTRequest.GetInt("templateid", 1)).Directory,
                                           config.Indexpage == 0 ? "forumindex.aspx" : "website.aspx",
                                           DNTRequest.GetInt("templateid", 1)); //当跳转模板页时,生成目标文件
                        }
                        CreateTemplate(forumPath, Templates.GetTemplateItem(int.Parse(strTemplateid)).Directory, requestPath.Substring(context.Request.Path.LastIndexOf("/")).Replace("/", ""), int.Parse(strTemplateid));
                    }

                    //通过参数设置指定模板
                    if (config.Specifytemplate > 0)
                    {
                        strTemplateid = SelectTemplate(strTemplateid, requestPath, context.Request.QueryString.ToString());
                    }
                    context.RewritePath(forumPath + "aspx/" + strTemplateid + requestPath.Substring(context.Request.Path.LastIndexOf("/")), string.Empty, context.Request.QueryString.ToString() + "&selectedtemplateid=" + strTemplateid);
                }

                else if (requestPath.StartsWith(forumPath + "archiver/"))
                {
                    //当使用伪aspx, 如:showforum-1.aspx等.
                    if (config.Aspxrewrite == 1)
                    {
                        string path = requestPath.Substring(forumPath.Length + 8);
                        foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                        {
                            if (Regex.IsMatch(path, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                            {
                                string newUrl = Regex.Replace(path, url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);

                                context.RewritePath(forumPath + "archiver" + url.Page, string.Empty, newUrl);
                                return;
                            }
                        }
                    }
                    return;
                }
                else if (requestPath.StartsWith(forumPath + "tools/"))
                {
                    //当使用伪aspx, 如:showforum-1.aspx等.
                    if (config.Aspxrewrite == 1)
                    {
                        string path = requestPath.Substring(forumPath.Length + 5);
                        foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                        {
                            if (Regex.IsMatch(path, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                            {
                                string newUrl = Regex.Replace(path, url.Pattern, Utils.UrlDecode(url.QueryString), Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);

                                context.RewritePath(forumPath + "tools" + url.Page, string.Empty, newUrl);
                                return;
                            }
                        }
                    }
                    return;
                }
                else if (requestPath.StartsWith(forumPath + "upload/") || requestPath.StartsWith(forumPath + "space/upload/") || requestPath.StartsWith(forumPath + "avatars/upload/"))
                {
                    context.RewritePath(forumPath + "index.aspx");
                    return;
                }
            }
        }
Example #29
0
        public static bool BackupDatabase(BaseConfigInfo bci, string file)
        {
            string tempPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "_temp/backupDB");

            if (Directory.Exists(tempPath))
            {
                DirectoryInfo d = new DirectoryInfo(tempPath);
                We7Helper.DeleteFileTree(d);
            }

            DatabaseInfo dbi     = GetDatabaseInfo(bci);
            string       dbFile  = dbi.DBFile.Replace("{$App}", AppDomain.CurrentDomain.BaseDirectory);
            bool         success = false;

            switch (bci.DBType.ToLower())
            {
            case "sqlite":
            case "access":
                File.Copy(dbFile, Path.Combine(tempPath, Path.GetFileName(file)), true);
                success = true;
                break;

            case "sqlserver":
                string masterString = String.Format("Server={0};Database={1};User={2};Password={3}", dbi.Server, "master", dbi.User, dbi.Password);
                string sql          = String.Format("backup database {0} to disk='{1}' with init", dbi.Database, Path.Combine(tempPath, Path.GetFileName(file)));

                //创建数据库
                IDbDriver driver = new SqlDbDriver();
                using (IConnection conn = driver.CreateConnection(masterString))
                {
                    SqlStatement st = new SqlStatement(sql);
                    driver.FormatSQL(st);
                    conn.Update(st);
                }
                success = true;
                break;

            case "mysql":

                break;
            }

            if (success)
            {
                string[] FileProperties = new string[2];
                FileProperties[0] = tempPath; //压缩目录
                FileProperties[1] = file;     //压缩后的目录
                if (File.Exists(FileProperties[1]))
                {
                    File.Delete(FileProperties[1]);
                }

                //压缩文件
                try
                {
                    ZipClass.ZipFileMain(FileProperties);
                }
                catch
                {
                }
            }

            return(success);
        }