diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..23a4065 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.vs +*.rar +*.zip +.Debug \ No newline at end of file diff --git a/.gitignore.bak b/.gitignore.bak new file mode 100644 index 0000000..07d3455 --- /dev/null +++ b/.gitignore.bak @@ -0,0 +1,4 @@ +.vs +*.rar +*.zip +Debug \ No newline at end of file diff --git a/HappyReading.sln b/HappyReading.sln new file mode 100644 index 0000000..958390a --- /dev/null +++ b/HappyReading.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28307.572 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HappyReading", "HappyReading\HappyReading.csproj", "{A7AAEB8A-9CDA-485D-88A5-15208889EDDA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A7AAEB8A-9CDA-485D-88A5-15208889EDDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A7AAEB8A-9CDA-485D-88A5-15208889EDDA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A7AAEB8A-9CDA-485D-88A5-15208889EDDA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A7AAEB8A-9CDA-485D-88A5-15208889EDDA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D93B108A-14B4-439B-9FF3-83E11E3D2ED4} + EndGlobalSection +EndGlobal diff --git a/HappyReading/App.config b/HappyReading/App.config new file mode 100644 index 0000000..8b5b41a --- /dev/null +++ b/HappyReading/App.config @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/HappyReading/App.xaml b/HappyReading/App.xaml new file mode 100644 index 0000000..eb9e786 --- /dev/null +++ b/HappyReading/App.xaml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + diff --git a/HappyReading/App.xaml.cs b/HappyReading/App.xaml.cs new file mode 100644 index 0000000..045b9c6 --- /dev/null +++ b/HappyReading/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace HappyReading +{ + /// + /// App.xaml 的交互逻辑 + /// + public partial class App : Application + { + } +} diff --git a/HappyReading/BLL/ConfigReadWrite.cs b/HappyReading/BLL/ConfigReadWrite.cs new file mode 100644 index 0000000..4b4acb9 --- /dev/null +++ b/HappyReading/BLL/ConfigReadWrite.cs @@ -0,0 +1,42 @@ +using HappyReading.DAL; +using HappyReading.Model; +using System; + +namespace HappyReading.BLL +{ + /// + /// 配置读写 + /// + class ConfigReadWrite + { + + /// + /// 写入配置 + /// + /// + public static void SetConfig(Config config) + { + ConfigHelper.SetConfig("Theme", config.Theme); + ConfigHelper.SetConfig("FontSize", config.FontSize.ToString()); + ConfigHelper.SetConfig("Typeface", config.Typeface); + ConfigHelper.SetConfig("SourceStation", config.SourceStation); + ConfigHelper.SetConfig("FattenNumber", config.FattenNumber.ToString()); + ConfigHelper.SetConfig("Width_height", config.Width_height); + } + + /// + /// 读取配置 + /// + public static Config GetConfig() + { + Config config = new Config(); + config.FontSize = Convert.ToInt32(ConfigHelper.GetConfig("FontSize")); + config.Typeface = ConfigHelper.GetConfig("Typeface"); + config.Theme = ConfigHelper.GetConfig("Theme"); + config.SourceStation= ConfigHelper.GetConfig("SourceStation"); + config.FattenNumber = Convert.ToInt32(ConfigHelper.GetConfig("FattenNumber")); + config.Width_height = ConfigHelper.GetConfig("Width_height"); + return config; + } + } +} diff --git a/HappyReading/BLL/DataFetch.cs b/HappyReading/BLL/DataFetch.cs new file mode 100644 index 0000000..5e2b1b7 --- /dev/null +++ b/HappyReading/BLL/DataFetch.cs @@ -0,0 +1,605 @@ +using HappyReading.DAL; +using HappyReading.Model; +using HappyReading.UI; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading; +using System.Windows; + +namespace HappyReading.BLL +{ + public class DataFetch + { + + /// + /// 路径 + /// + public static string Path = AppDomain.CurrentDomain.BaseDirectory; + + + /// + /// 软件更新 + /// + public static void SoftwareUpdate() + { + try + { + Update update = JsonHelper.DeserializeJsonToObject(GetHtml.GetHttp("https://script.haokaikai.cn/Update/HappyReading.json")); + if (update.State == 1) + { + MessageBox.Show(update.Msg, "软件暂停使用"); + //关闭全部窗体并退出程序使用 + Application.Current.Shutdown(); + return; + } + + if (Config.Edition != update.Edition) + { + MessageBox.Show(update.Msg + "\n更新日期:" + update.UpdateDate + "\n点击确定后会自动打开下载地址!", "更新提示"); + //打开网页 + System.Diagnostics.Process.Start(update.Download); + } + } + catch (Exception ex) + { + Tool.TextAdditional(ex.Message); + } + } + + /// + /// 判断指定表中是否存在某列 + /// + /// 表名 + /// 列名 + /// 如果存在返回true + public static bool ColumnExistence(string table, string column) + { + //获取指定表的全部列信息 + DataTable dt = SQLiteDBHelper.ExecuteDataTable("PRAGMA table_info([" + table + "])", null); + foreach (DataRow myRow in dt.Rows) + { + if (myRow[1].ToString() == column) return true; + } + return false; + } + + + + /// + /// 获取我的书架 + /// + /// 判断是否为养肥区,默认不是 + /// + public static List GetBooks(bool fattening=false) + { + int Fattening = fattening ? 1 : 0; + + //获取DataTable + DataTable dt = SQLiteDBHelper.ExecuteDataTable("select *from Books where Fattening="+ Fattening, null); + List Books= ModelConvertHelper.DataTableToList(dt); + + foreach (Book book in Books) + { + book.Newest = Tool.InterceptStr(book.Newest); + book.Name= Tool.InterceptStr(book.Name); + } + + //获取所有书籍 + return Books; + } + + /// + /// 根据链接来获取书源 + /// + /// 链接 + /// 返回书源,如果不存在则返回null + public static BookSource URLGetBookSource(string URL) + { + string[] Urls = URL.Split(new string[] { "://", "/" }, StringSplitOptions.RemoveEmptyEntries); + foreach (BookSource bookSource in TempData.GetBookSourceS()) + { + if (URL.Contains(bookSource.Url) || URL.Contains(bookSource.SearchUrl)|| bookSource.Url.Contains(Urls[1])|| bookSource.SearchUrl.Contains(Urls[1])) + { + return bookSource; + } + } + + return null; + } + + + /// + /// 更新全部书籍 + /// + public static void BooksUpdate(object ob) + { + //获取全部书籍 + DataTable dt = SQLiteDBHelper.ExecuteDataTable("select *from Books", null); + List Books = ModelConvertHelper.DataTableToList(dt); + foreach (Book book in Books) + { + //获取初始搜索文本 + string html = GetHtml.GetHttpWebRequest(book.Url); + + BookSource bs = GetBookSource(book.Source); + + //检测书源有效性 + if (bs.Title is null) + { + App.Current.Dispatcher.Invoke((Action)(() => + { + new Tips(book.Name + "的书源发现异常,请检查书源是否被删除或禁用!").Show(); + return; + })); + + } + //获取最新章节 + string LatestChapters = Tool.GetRegexStr(html, bs.NewestRegular).Trim(); + + //获取更新时间 + string Update = Tool.GetRegexStr(html, bs.UpdateRegular).Trim(); + + SQLiteDBHelper.ExecuteNonQuery("Update Books set 'Newest' = '"+ LatestChapters + "', 'Update' = '"+ Tool.GetUpdataDate(Update) + "' where Id =" + book.Id, null); + } + ((MainWindow)ob).Dispatcher.Invoke(new Action(() => + { + ((MainWindow)ob).DataContext = DataFetch.GetBooks(); + })); + } + + /// + /// 获取全部书源 + /// + /// 状态1代表只获取正常的书源,如果为其他则获取全部书源 + /// + public static List GetBookSources(int State=1) + { + //获取DataTable + DataTable dt; + if (State == 1) + { + //获取DataTable + dt = SQLiteDBHelper.ExecuteDataTable("select *from BookSource where State=1", null); + } + else + { + //获取DataTable + dt = SQLiteDBHelper.ExecuteDataTable("select *from BookSource", null); + } + + //获取所有书源 + return ModelConvertHelper.DataTableToList(dt); + } + + /// + /// 更新书源状态 + /// + public static void UpdateSourceState() + { + Thread thread = new Thread(new ThreadStart(delegate + { + //遍历源站 + foreach (BookSource bookSource in GetBookSources(0)) + { + //1代表网站可以访问,0代表不可以访问 + int state = GetHtml.GetUnicom(bookSource.Url) ? 1 : 0; + UpdateState((int)bookSource.Id, state); + } + App.Current.Dispatcher.Invoke((Action)(() => + { + TempData.UpdateBookSourceS(); + })); + + })); + thread.IsBackground = true; + thread.Start(); + } + + /// + /// 搜索书籍 + /// + /// 书源 + /// 书名关键词 + /// 返回搜索结果 + public static List Search(BookSource bookSource,string Keyword) + { + /* + //这里先判断是否是全部书源搜索 + if (bookSource.Id == -5) + { + List Books = new List(); + foreach (BookSource Source in TempData.GetBookSourceS()) + { + try + { + if (Books.Count <= 0) + { + List T_books = Search(Source, Keyword); + if (T_books != null) + { + Books = T_books; + } + } + else + { + Books = Books.Concat(Search(Source, Keyword)).ToList(); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + Tool.TextAdditional(ex.Message); + } + } + return Books; + }*/ + + //获取编码 + string Code = GetHtml.GetCode(bookSource.SearchUrl); + + //忽略大小写进行比较 + if (!Code.Equals("utf-8", StringComparison.OrdinalIgnoreCase)) + { + if (Code.Trim().Length <= 0) + { + Code = "utf-8"; + } + //这里处理一下keyword + Keyword = Tool.EncodingConvert(Keyword, Encoding.GetEncoding(Code)); + } + //存放书籍的书架 + List books = new List(); + + //获取初始搜索文本 + string html = GetHtml.GetHttpWebRequest(bookSource.SearchUrl + Keyword.Trim()); + + //获取搜索书籍范围 + string htmlRange = Tool.GetRegexStr(html, bookSource.AddressRangeRegular).Trim(); + + //分割搜索书籍 + string[] bookList = htmlRange.Split(new string[] { bookSource.AddressCuttingRegular }, StringSplitOptions.RemoveEmptyEntries); + + //遍历搜索到的书籍 + for (int i = 0; i < bookList.Length; i++) + { + //获取到书籍地址(对链接做出处理) + string BookUrl = Tool.ObtainUrl(bookSource.Url, Tool.GetRegexStr(bookList[i], bookSource.AddressRegular)); + + //防止因为找不到书籍而导致的错误 + if (BookUrl.Length <= 3) + { + continue; + } + + string BookHtml = GetHtml.GetHttpWebRequest(BookUrl); + + //获取书籍名称 + string BookName = Tool.GetRegexStr(BookHtml, bookSource.BookNameRegular); + + //书名都不存在,自然需要跳过本次循环 + if (BookName.Length <= 0) + { + continue; + } + + //获取作者 + string BookAuthor = Tool.GetRegexStr(BookHtml, bookSource.AuthorRegular); + + //获取更新时间 + string BookUpdate = Tool.GetUpdataDate(Tool.GetRegexStr(BookHtml, bookSource.UpdateRegular)); + + //获取最新章节名称 + string BookNewest = Tool.GetRegexStr(BookHtml, bookSource.NewestRegular); + + //获取源站名称 + string BookSource = bookSource.Title; + + //封面图 + string BookImage = Tool.GetRegexStr(BookHtml, bookSource.ImageRegular); + + //更新状态 + string BookUpdateState = Tool.GetRegexStr(BookHtml, bookSource.StateRegular); + + //简介 + string BookDetails = Tool.GetRegexStr(BookHtml, bookSource.DetailsRegular); + + books.Add(new Book { Author = BookAuthor, Update = BookUpdate, Name = BookName, Source = BookSource, Newest = BookNewest, Url = BookUrl, Details = BookDetails, Image = BookImage, UpdateState = BookUpdateState }); + } + + if (books.Count <= 0) + { + return null; + } + return books; + } + + + /* + /// + /// 所有源站遍历搜索某书 + /// + /// 书籍信息 + /// 返回所有源搜索结果 + public static List SourceSearch(Book Works) + { + string BookName = Works.Name; + List bookSources = TempData.GetBookSourceS(); + //存储书的书架 + List Books = new List(); + foreach (BookSource bookSource in bookSources) + { + List books = Search(bookSource, BookName); + if (books != null) + { + foreach (Book book in books) + { + if (book.Name == BookName || book.Author == Works.Author && book.Name.Contains(BookName)) + { + book.Id = Works.Id; + Books.Add(book); + } + } + } + + } + return Books; + }*/ + + + /// + /// 根据Id获取书籍的信息 + /// + /// 书籍的Id + /// 书籍的具体信息 + public static Book GetBook(int Id) + { + + //获取DataTable + DataTable dt = SQLiteDBHelper.ExecuteDataTable("select *from Books where Id=" + Id, null); + + //获取指定ID书籍的对象 + Book book = DAL.ModelConvertHelper.DataTableToModel(dt); + + //判断是否为NULL + if (book != null && book is Book) + { + return book; + } + + return null; + + } + + + /// + /// 获取书籍目录 + /// + /// + public static void GetList(Book book) + { + BookSource bs = GetBookSource(book.Source); + + Dictionary NewList = new Dictionary(); + + //范围 + string temp_str= Tool.GetRegexStr(GetHtml.GetHttpWebRequest(book.Url), bs.DirectoryScopeRegular); + //分割 + string [] temp_strs= temp_str.Split(new string[] { bs.DirectoryCuttingRegular }, StringSplitOptions.RemoveEmptyEntries); + + foreach (string tempStr in temp_strs) + { + string Title = Tool.GetRegexStr(tempStr, bs.DirectoryTieleRegular); + string Url = Tool.ObtainUrl(bs.Url, Tool.GetRegexStr(tempStr, bs.DirectoryUrlRegular), book.Url); + + //如果标题相同就会报错,所以这里回家进行简单的处理 + if (!NewList.ContainsKey(Title)&& Title.Trim().Length>2) + { + NewList.Add(Title, Url); + } + /* 这里加上后会重复显示 + else + { + NewList.Add(Title + Guid.NewGuid(), Url); + }*/ + + } + book.ListUrl = NewList; + + } + + + /// + /// 更换书籍的源 + /// + /// 书籍信息 + /// 返回更改结果 + public static bool UpdateBookSource(Book book) + { + string sql = "update Books set Url='" + book.Url + "',UpdateState = '" + book.UpdateState + "',Details = '" + book.Details + "',Author = '" + book.Author + "',Source = '" + book.Source + "',Image = '" + book.Image + "',Newest = '" + book.Newest + "','Update' = '" + book.Update + "' where Id = " + book.Id; + return (SQLiteDBHelper.ExecuteNonQuery(sql, null) <= 0) ? false : true; + //需要更新作者、更新日期、最新章节、书籍地址、书源信息、封面图 + } + + /// + /// 更新阅读章节数 + /// + /// 书籍ID + /// 阅读章节数 + /// + public static bool UpdateUpdateReadingBook(int Id,int Read) + { + return (SQLiteDBHelper.ExecuteNonQuery("update Books set Read='"+ Read + "' where Id=" + Id, null) <= 0) ? false : true; + } + + + /// + /// 删除指定Id的书籍 + /// + /// + /// 返回删除结果 + public static bool DeleteBook(int Id) + { + return (SQLiteDBHelper.ExecuteNonQuery("Delete from Books where Id=" + Id, null) <= 0) ? false : true; + } + + + /// + /// 删除书源 + /// + /// 书源ID + /// 返回删除结果 + public static bool DeleteBookSource(int Id) + { + return (SQLiteDBHelper.ExecuteNonQuery("Delete from BookSource where Id=" + Id, null) <= 0) ? false : true; + } + + + + /// + /// 根据书源名获取书源对象 + /// + /// 书源名 + /// 返回书源对象 + public static BookSource GetBookSource(string SourceName) + { + //获取DataTable + DataTable dt = SQLiteDBHelper.ExecuteDataTable("select *from BookSource where Title='" + SourceName+ "' and State!=0", null); + + //获取指定ID书籍的对象 + BookSource source = DAL.ModelConvertHelper.DataTableToModel(dt); + + return source; + } + + + /// + /// 获取目录数 + /// + /// 书籍对象 + /// 返回目录数 + public static int GetListCount(Book book) + { + //获取初始搜索文本 + string html = GetHtml.GetHttpWebRequest(book.Url); + + BookSource bs = GetBookSource(book.Source); + + //获取书籍范围 + string htmlRange = Tool.GetRegexStr(html, bs.DirectoryScopeRegular).Trim(); + + //分割章节 + string[] bookList = htmlRange.Split(new string[] { bs.DirectoryCuttingRegular}, StringSplitOptions.RemoveEmptyEntries); + + return bookList.Length; + } + + /// + /// 更新书源状态 + /// + /// 书源ID + /// 书源状态 + /// + public static bool UpdateState(int id, int state) + { + string sql = "update BookSource set State="+state+" where Id="+id; + return (SQLiteDBHelper.ExecuteNonQuery(sql, null) <= 0) ? false : true; + } + + + /// + /// 加入或者移出养肥区 + /// + /// 书籍ID + /// true为加入养肥区 + /// + public static bool Add_MoveOut(int id,bool state=false) + { + + int fatten = state ? 1 : 0; + string sql = "update Books set Fattening=" + fatten + " where Id=" + id; + return (SQLiteDBHelper.ExecuteNonQuery(sql, null) <= 0) ? false : true; + } + + + /// + /// 增加书源 + /// + /// 书源内容 + /// 返回结果 + public static bool SourceAdd(BookSource bookSource) + { + //增加之前先判断是否已经存在该书源 + + int count= Convert.ToInt32(SQLiteDBHelper.ExecuteScalar("select count(*) as count from BookSource where Url='" + bookSource.Url + "' or Title='" + bookSource.Title + "'", "count")); + + if (count > 0) + { + return false; + } + + + string sql= "INSERT INTO BookSource('Title','Url','SearchUrl','AddressRangeRegular','AddressCuttingRegular','AddressRegular','BookNameRegular','AuthorRegular','UpdateRegular','NewestRegular','DetailsRegular','StateRegular','DirectoryScopeRegular','DirectoryCuttingRegular','DirectoryTieleRegular','DirectoryUrlRegular','ContentTitleRegular','ContentRegular','ImageRegular','State') VALUES('" + bookSource.Title+"', '"+bookSource.Url+"', '"+bookSource.SearchUrl+"', '"+bookSource.AddressRangeRegular+"', '"+bookSource.AddressCuttingRegular+"', '"+bookSource.AddressRegular+ "','" + bookSource.BookNameRegular + "', '" + bookSource.AuthorRegular+"', '"+bookSource.UpdateRegular+"', '"+bookSource.NewestRegular+"', '"+bookSource.DetailsRegular+"', '"+bookSource.StateRegular+"', '"+bookSource.DirectoryScopeRegular+"', '"+bookSource.DirectoryCuttingRegular+"', '"+bookSource.DirectoryTieleRegular+"', '"+bookSource.DirectoryUrlRegular+"', '"+bookSource.ContentTitleRegular+"', '"+bookSource.ContentRegular+"', '"+bookSource.ImageRegular+"'," +bookSource.State+")"; + + TempData.UpdateBookSourceS(); + + return (SQLiteDBHelper.ExecuteNonQuery(sql, null) <= 0) ? false : true; + } + + + /// + /// 更新书源 + /// + /// + /// + public static bool SourceUpdate(BookSource bookSource) + { + string sql = "update BookSource set 'Title'='" + bookSource.Title + "','Url'='" + bookSource.Url + "','SearchUrl'='" + bookSource.SearchUrl + "','AddressRangeRegular'='"+ bookSource.AddressRangeRegular + "','AddressCuttingRegular'='" + bookSource.AddressCuttingRegular + "','AddressRegular'='" + bookSource.AddressRegular + "','BookNameRegular'='" + bookSource.BookNameRegular + "','AuthorRegular'='" + bookSource.AuthorRegular + "','UpdateRegular'='" + bookSource.UpdateRegular + "','NewestRegular'='" + bookSource.NewestRegular + "','DetailsRegular'='" + bookSource.DetailsRegular + "','StateRegular'='" + bookSource.StateRegular + "','DirectoryScopeRegular'='" + bookSource.DirectoryScopeRegular + "','DirectoryCuttingRegular'='" + bookSource.DirectoryCuttingRegular + "','DirectoryTieleRegular'='" + bookSource.DirectoryTieleRegular + "','DirectoryUrlRegular'='" + bookSource.DirectoryUrlRegular + "','ContentTitleRegular'='" + bookSource.ContentTitleRegular + "','ContentRegular'='"+ bookSource.ContentRegular + "','ImageRegular'='"+ bookSource.ImageRegular + "' where Id="+ bookSource.Id; + //TempData.UpdateBookSourceS(); + return (SQLiteDBHelper.ExecuteNonQuery(sql, null) <= 0) ? false : true; + } + + /// + /// 添加书籍 + /// + /// 书籍对象 + /// 返回添加的结果 + public static bool BookAdd(Book book) + { + if (BoolBookAdd(book.Name)) + { + App.Current.Dispatcher.Invoke((Action)(() => + { + new Tips(book.Name + "的书源发现异常,请检查书源是否被删除或禁用!").Show(); + + })); + return false; + } + + string sql= "INSERT INTO Books('Name','Url','UpdateState','Details','Author','Source','Image','Newest','Update','Read','ReadChapter') VALUES('" + + book.Name+"', '" + +book.Url+"', '" + +book.UpdateState + "', '" + +book.Details + "', '" + +book.Author+"', '" + +book.Source+"', '" + +book.Image+"', '" + +book.Newest+"', '" + +book.Update+"',0, '')"; + return (SQLiteDBHelper.ExecuteNonQuery(sql, null) <= 0) ? false : true; + } + + /// + /// 书架中是否存在该书籍 + /// + /// 书籍名称 + /// 返回查询结果 + public static bool BoolBookAdd(string BookName) + { + string Sql = "select count(*) as 次数 from Books where Name='"+BookName+"'"; + return (Convert.ToInt32(SQLiteDBHelper.ExecuteScalar(Sql, "次数")) > 0) ? true : false; + } + } +} diff --git a/HappyReading/BLL/GetHtml.cs b/HappyReading/BLL/GetHtml.cs new file mode 100644 index 0000000..5030e59 --- /dev/null +++ b/HappyReading/BLL/GetHtml.cs @@ -0,0 +1,172 @@ +using HappyReading.DAL; +using HappyReading.Model; +using System; +using System.IO; +using System.Net; +using System.Text; +using System.Threading; + +namespace HappyReading.BLL +{ + class GetHtml + { + + /// + /// 带浏览器信息抓取网页(utf-8) + /// + /// 网页地址 + /// + public static string GetHttp(string url, string Code= "utf-8") + { + try + { + Uri uri = new Uri(url); + HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri); + myReq.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705"; + myReq.Accept = "*/*"; + myReq.KeepAlive = true; + myReq.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5"); + + //设置超时时间为15秒 + myReq.Timeout = 15000; + HttpWebResponse result = (HttpWebResponse)myReq.GetResponse(); + + Stream receviceStream = result.GetResponseStream(); + StreamReader readerOfStream = new StreamReader(receviceStream,Encoding.GetEncoding(Code)); + string strHTML = readerOfStream.ReadToEnd(); + readerOfStream.Close(); + receviceStream.Close(); + result.Close(); + return strHTML; + } + catch(Exception ex) + { + Tool.TextAdditional(ex.Message); + return null; + } + } + + + + /// + /// 获取网页内容 + /// + /// 需要查询的链接 + /// + public static string GetHttpWebRequest(string url) + { + try + { + //网站编码 + string code = TempData.GetUrlCode(url); + return GetHttp(url, code); + } + catch(Exception ex) + { + Tool.TextAdditional(ex.Message); + return GetHttp(url, GetCode(url)); + } + } + + + /// + /// 获取网页内容 + /// + /// 需要查询的链接 + /// + public static string GetHttpWebRequest(string url,string keyword) + { + try + { + //把网址分割,取出域名部分 + string[] Urls = url.Split(new string[] { "://", "/" }, StringSplitOptions.RemoveEmptyEntries); + if (!TempData.UrlCode.ContainsKey(Urls[1])) + { + TempData.UrlCode[Urls[1]] = GetCode(url); + } + + //网站编码 + string code = TempData.UrlCode[Urls[1]]; + return GetHttp(url, code); + } + catch + { + Tool.TextAdditional("获取网页内容失败"); + return GetHttp(url, GetCode(url)); + } + } + + + /// + /// 智能判断网站编码 + /// + /// + /// + public static string GetCode(string url) + { + + //网站编码 + string Code = string.Empty; + + string html = GetHttp(url); + if (html==null) + { + return ""; + } + + ; + if ((Code = Tool.GetRegexStr(html, "charset=\"([\\s\\S]*?)\"").Trim()).Length > 2) return Code; + + + if ((Code = Tool.GetRegexStr(html, "charset=([\\s\\S]*?)\"").Trim()).Length > 2) return Code; + + if (html.Contains("charset=gbk") || html.Contains("charset=GBK")) + { + return "GBK"; + } + else if (html.Contains("charset=GB2312") || html.Contains("charset=gb2312")) + { + return "GB2312"; + } + + //如果获取不到编码,那就默认为utf-8 + if (Code.Length <= 0) + { + return "utf-8"; + } + return Code; + + } + + + /// + /// 检测网站是否返回码为200 + /// + /// 判断的链接 + /// + public static bool GetUnicom(string url) + { + string StatusCode = null; + try + { + HttpWebRequest req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url)); + req.Method = "HEAD"; + req.Timeout = 30000; + HttpWebResponse res = (HttpWebResponse)req.GetResponse(); + StatusCode = res.StatusCode.ToString(); + if (StatusCode == "OK") + { + return true; + } + } + catch (WebException ex) + { + Console.WriteLine(ex.ToString()); + Tool.TextAdditional(ex.Message); + return false; + } + return false; + } + + } +} diff --git a/HappyReading/BLL/HotKey.cs b/HappyReading/BLL/HotKey.cs new file mode 100644 index 0000000..d6eaa07 --- /dev/null +++ b/HappyReading/BLL/HotKey.cs @@ -0,0 +1,65 @@ +using System; +using System.Runtime.InteropServices; + +namespace HappyReading.BLL +{ + /// + /// 热键类 + /// + class HotKey + { + /// + /// 如果函数执行成功,返回值不为0。 + /// 如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。.NET方法:Marshal.GetLastWin32Error() + /// + /// 要定义热键的窗口的句柄 + /// 定义热键ID(不能与其它ID重复) + /// 标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效 + /// 定义热键的内容,WinForm中可以使用Keys枚举转换, + /// WPF中Key枚举是不正确的,应该使用System.Windows.Forms.Keys枚举,或者自定义正确的枚举或int常量 + /// + [DllImport("user32.dll", SetLastError = true)] + public static extern bool RegisterHotKey( + IntPtr hWnd, + int id, + KeyModifiers fsModifiers, + int vk + ); + /// + /// 取消注册热键 + /// + /// 要取消热键的窗口的句柄 + /// 要取消热键的ID + /// + [DllImport("user32.dll", SetLastError = true)] + public static extern bool UnregisterHotKey( + IntPtr hWnd, + int id + ); + /// + /// 向全局原子表添加一个字符串,并返回这个字符串的唯一标识符,成功则返回值为新创建的原子ID,失败返回0 + /// + /// + /// + [DllImport("kernel32", SetLastError = true)] + public static extern short GlobalAddAtom(string lpString); + [DllImport("kernel32", SetLastError = true)] + public static extern short GlobalDeleteAtom(short nAtom); + /// + /// 定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值) + /// + [Flags()] + public enum KeyModifiers + { + None = 0, + Alt = 1, + Ctrl = 2, + Shift = 4, + WindowsKey = 8 + } + /// + /// 热键的对应的消息ID + /// + public const int WM_HOTKEY = 0x312; + } +} diff --git a/HappyReading/BLL/Tool.cs b/HappyReading/BLL/Tool.cs new file mode 100644 index 0000000..5d334a9 --- /dev/null +++ b/HappyReading/BLL/Tool.cs @@ -0,0 +1,350 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading; +using System.Windows.Controls; +using System.Windows.Markup; +using System.Windows.Media; + +namespace HappyReading.BLL +{ + public class Tool + { + /// + /// 更新日期格式化 + /// + /// 更新日期 + /// 格式化的文本 + public static string GetUpdataDate(string date) + { + if (date.Length <= 1) + { + Console.WriteLine("时间获取失败~"); + return ""; + } + + try + { + DateTime Getdate = Convert.ToDateTime(date); + DateTime newDate = DateTime.Now; + TimeSpan timeSpan = newDate - Getdate; + + //一小时内 + if (timeSpan.TotalMinutes < 60 && timeSpan.TotalHours < 1) + { + return (int)timeSpan.TotalMinutes + "分前"; + } + + //24小时内 + if (timeSpan.TotalHours < 24 && (int)timeSpan.TotalHours > 1) + { + return (int)timeSpan.TotalHours + "小时前"; + } + + //月 + if (timeSpan.TotalDays > 30 && timeSpan.TotalDays < 365) + { + return ((int)timeSpan.TotalDays / 30) + "月前"; + } + + //年 + if (timeSpan.TotalDays > 365) + { + return ((int)timeSpan.TotalDays / 365) + "年前"; + } + + return (int)timeSpan.TotalDays + "天前"; + } + catch + { + return "获取失败"; + } + + } + + /// + /// Text文件追加 + /// + /// 追加内容 + /// 返回追加结果 + public static bool TextAdditional(string text) + { + FileStream fs = null; + string filePath = AppDomain.CurrentDomain.BaseDirectory+"MsgLog.txt"; + // 将待写的入数据从字符串转换为字节数组 + Encoding encoder = Encoding.UTF8; + byte[] bytes = encoder.GetBytes(DateTime.Now.ToString("G")+":"+text + "\r\n"); + try + { + fs = File.OpenWrite(filePath); + // 设定书写的开始位置为文件的末尾 + fs.Position = fs.Length; + // 将待写入内容追加到文件末尾 + fs.Write(bytes, 0, bytes.Length); + fs.Close(); + fs.Dispose(); + return true; + } + catch + { + return false; + } + + } + + /// + /// 智能拼凑URL + /// + /// 主页 + /// 链接 + /// 目录页 + /// 返回处理的链接 + public static string ObtainUrl(string host, string url, string BookListUrl = null) + { + if (url.Length > 0) + { + if (url.StartsWith("http")) + { + return url; + } + else if (url.Substring(0, 1) == "/") + { + return host + url; + } + else + { + if (BookListUrl == null) return host + url; + + return BookListUrl + url; + } + } + return url; + } + + + /// + /// 编码转换 + /// + /// 需要转的字符串 + /// 将要转成的编码 + /// 返回转码结果 + public static string EncodingConvert(string fromString, Encoding toEncoding) + { + return System.Web.HttpUtility.UrlEncode(fromString, toEncoding); + } + + + /// + /// 获取系统中文字体 + /// + /// 返回字体列表 + public static List GetTypeface() + { + List Typeface = new List(); + foreach (FontFamily fontfamily in Fonts.SystemFontFamilies) + { + LanguageSpecificStringDictionary fontdics = fontfamily.FamilyNames; + + //判断该字体是不是中文字体 英文字体为en-us + if (fontdics.ContainsKey(XmlLanguage.GetLanguage("zh-cn"))) + { + string fontfamilyname = null; + if (fontdics.TryGetValue(XmlLanguage.GetLanguage("zh-cn"), out fontfamilyname)) + { + Typeface.Add(fontfamilyname); + } + } + } + return Typeface; + } + + + + /// + /// 正则查找 + /// + /// 正文 + /// 正则表达式 + /// 返回结果(单条数据) + public static string GetRegexStr(string reString, string regexCode) + { + try + { + System.Text.RegularExpressions.Regex reg;//正则表达式变量 + reg = new System.Text.RegularExpressions.Regex(regexCode);//初始化正则对象 + + System.Text.RegularExpressions.MatchCollection mc = reg.Matches(reString);//匹配; + string temp = string.Empty;//声明一个临时变量 + for (int ic = 0; ic < mc.Count; ic++) + { + System.Text.RegularExpressions.GroupCollection gc = mc[ic].Groups;//获取所有分组 + System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection(); + for (int i = 0; i < gc.Count; i++) + { + temp = gc[i].Value; //得到组对应数据 + } + } + return temp; + } + catch + { + TextAdditional("正则查找失败"); + return string.Empty; + } + + } + + /// + /// 获取名称 + /// + /// 输入字段 + /// 返回名称 + public static string GetName(string str) + { + if (str.StartsWith("([\\s\\S]*?)").Trim(); + } + return str; + } + + + /// + /// 获取链接 + /// + /// + /// + public static string GetUrl(string str) + { + if (str.StartsWith(" + /// 自由html过滤系统 + /// + /// html字符 + /// 过滤过的字符串 + public static string HtmlFilter(string strHtml) + { + if (string.IsNullOrEmpty(strHtml)) return strHtml; + + string countbr =GetRegexStr(strHtml, "
\\s+
"); + if (countbr != "" || countbr.Length > 1) + { + strHtml = strHtml.Replace(countbr, "\r\n\r\n"); + } + + strHtml = strHtml.Replace("", ""); + strHtml = strHtml.Replace(""); + strHtml = strHtml.Replace("<", "<"); + strHtml = strHtml.Replace(" ", " "); + strHtml = strHtml.Replace("
", "\r\n"); + strHtml = strHtml.Replace("
", "\r\n"); + strHtml = strHtml.Replace("
", "\r\n"); + strHtml = strHtml.Replace("", ""); + strHtml = strHtml.Replace("", ""); + strHtml = strHtml.Replace("X23US.COM更新最快", ""); + strHtml = strHtml.Replace("X23US.COM", ""); + strHtml = strHtml.Replace("最快更新", ""); + strHtml = strHtml.Replace("最新章节!", ""); + strHtml = strHtml.Replace("最新章节", ""); + strHtml = strHtml.Replace("小说网..org", ""); + strHtml = strHtml.Replace("更新最快", ""); + strHtml = strHtml.Replace("23US.COM", ""); + strHtml = strHtml.Replace("23US.COM", ""); + strHtml = strHtml.Replace("&", ""); + strHtml = strHtml.Replace("nbsp;", ""); + strHtml = strHtml.Replace(";;", ""); + strHtml = strHtml.Replace("『3¥3小说网→』﹃值得收藏的网络小說阅读网", ""); + strHtml = strHtml.Replace("", ""); + strHtml = strHtml.Replace("", ""); + strHtml = strHtml.Replace("readx();", ""); + strHtml = strHtml.Replace("style=\"text-align: center\">", ""); + strHtml = strHtml.Replace("“", "“"); + strHtml = strHtml.Replace("”", "”"); + strHtml = strHtml.Replace("…", "…"); + strHtml = strHtml.Replace("

", ""); + strHtml = strHtml.Replace("

", "\r\n\r\n"); + + return strHtml.Trim(); + } + + + /// + /// 获取中英文混排字符串的实际长度(字节数) + /// + /// 要获取长度的字符串 + /// 字符串的实际长度值(字节数) + public static int GetStringLength(string str) + { + if (str.Equals(string.Empty)) + return 0; + int strlen = 0; + ASCIIEncoding strData = new ASCIIEncoding(); + //将字符串转换为ASCII编码的字节数字 + byte[] strBytes = strData.GetBytes(str); + for (int i = 0; i <= strBytes.Length - 1; i++) + { + if (strBytes[i] == 63) //中文都将编码为ASCII编码63,即"?"号 + strlen++; + strlen++; + } + return strlen; + } + + //计算文字的长度 + public static int Select(double fontSzie,string str) + { + TextBlock temp_tb = new TextBlock(); + temp_tb.FontSize = fontSzie; + temp_tb.Text = "我"; + //actualWidth + + /* + * 一行最多有42个字符 + * 最多可以有22行 + * 那么总共就是22*42=924个字符 + * 一个字符宽17.86 高13.41 + * + */ + + double sizeWidth = temp_tb.ActualWidth; + + double count = 750 / sizeWidth; + + TextBlock tb = new TextBlock(); + tb.FontSize = fontSzie; + tb.Text = str; + + return 0; + } + + + + /// + /// 截取超过长度的字符串 + /// + /// + /// + public static string InterceptStr(string str) + { + if (str.Length > 13) + { + return str.Substring(0, 12) + "…"; + } + return str; + } + } +} diff --git a/HappyReading/DAL/ConfigHelper.cs b/HappyReading/DAL/ConfigHelper.cs new file mode 100644 index 0000000..500d400 --- /dev/null +++ b/HappyReading/DAL/ConfigHelper.cs @@ -0,0 +1,105 @@ +using HappyReading.BLL; +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Management; +using System.Text; +using System.Threading.Tasks; + +namespace HappyReading.DAL +{ + public class ConfigHelper + { + /// + /// 根据键值获取配置文件 + /// + /// 键值 + /// + public static string GetConfig(string key) + { + string val = string.Empty; + if (ConfigurationManager.AppSettings.AllKeys.Contains(key)) + val = ConfigurationManager.AppSettings[key]; + return val; + } + + /// + /// 获取所有配置文件 + /// + /// + public static Dictionary GetConfig() + { + Dictionary dict = new Dictionary(); + foreach (string key in ConfigurationManager.AppSettings.AllKeys) + dict.Add(key, ConfigurationManager.AppSettings[key]); + return dict; + } + + /// + /// 根据键值获取配置文件 + /// + /// 键值 + /// 默认值 + /// + public static string GetConfig(string key, string defaultValue) + { + string val = defaultValue; + if (ConfigurationManager.AppSettings.AllKeys.Contains(key)) + val = ConfigurationManager.AppSettings[key]; + if (val == null) + val = defaultValue; + return val; + } + + /// + /// 写配置文件,如果节点不存在则自动创建 + /// + /// 键值 + /// 值 + /// + public static bool SetConfig(string key, string value) + { + try + { + Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); + if (!conf.AppSettings.Settings.AllKeys.Contains(key)) + conf.AppSettings.Settings.Add(key, value); + else + conf.AppSettings.Settings[key].Value = value; + conf.Save(); + return true; + } + catch(Exception ex) + { + Tool.TextAdditional(ex.Message); + return false; } + } + + /// + /// 写配置文件(用键值创建),如果节点不存在则自动创建 + /// + /// 键值集合 + /// + public static bool SetConfig(Dictionary dict) + { + try + { + if (dict == null || dict.Count == 0) + return false; + Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); + foreach (string key in dict.Keys) + { + if (!conf.AppSettings.Settings.AllKeys.Contains(key)) + conf.AppSettings.Settings.Add(key, dict[key]); + else + conf.AppSettings.Settings[key].Value = dict[key]; + } + conf.Save(); + return true; + } + catch(Exception ex) + { Tool.TextAdditional(ex.Message); return false; } + } + } +} diff --git a/HappyReading/DAL/JsonHelper.cs b/HappyReading/DAL/JsonHelper.cs new file mode 100644 index 0000000..b9c0815 --- /dev/null +++ b/HappyReading/DAL/JsonHelper.cs @@ -0,0 +1,66 @@ +using Newtonsoft.Json; +using System.Collections.Generic; +using System.IO; + +namespace HappyReading.DAL +{ + /// + /// Json帮助类 + /// + class JsonHelper + { + /// + /// 将对象序列化为JSON格式 + /// + /// 对象 + /// json字符串 + public static string SerializeObject(object o) + { + string json = JsonConvert.SerializeObject(o); + return json; + } + + /// + /// 解析JSON字符串生成对象实体 + /// + /// 对象类型 + /// json字符串(eg.{"ID":"112","Name":"石子儿"}) + /// 对象实体 + public static T DeserializeJsonToObject(string json) where T : class + { + JsonSerializer serializer = new JsonSerializer(); + StringReader sr = new StringReader(json); + object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T)); + T t = o as T; + return t; + } + + /// + /// 解析JSON数组生成对象实体集合 + /// + /// 对象类型 + /// json数组字符串(eg.[{"ID":"112","Name":"石子儿"}]) + /// 对象实体集合 + public static List DeserializeJsonToList(string json) where T : class + { + JsonSerializer serializer = new JsonSerializer(); + StringReader sr = new StringReader(json); + object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List)); + List list = o as List; + return list; + } + + /// + /// 反序列化JSON到给定的匿名对象. + /// + /// 匿名对象类型 + /// json字符串 + /// 匿名对象 + /// 匿名对象 + public static T DeserializeAnonymousType(string json, T anonymousTypeObject) + { + T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject); + return t; + } + } +} diff --git a/HappyReading/DAL/ModelConvertHelper.cs b/HappyReading/DAL/ModelConvertHelper.cs new file mode 100644 index 0000000..d19a0ca --- /dev/null +++ b/HappyReading/DAL/ModelConvertHelper.cs @@ -0,0 +1,184 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace HappyReading.DAL +{ + /// + /// 实体转换辅助类 + /// + public class ModelConvertHelper where T : new() + { + /// + /// List泛型转换DataTable. + /// + public DataTable ListToDataTable(List items) + { + var tb = new DataTable(typeof(T).Name); + + PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo prop in props) + { + Type t = GetCoreType(prop.PropertyType); + tb.Columns.Add(prop.Name, t); + } + + foreach (T item in items) + { + var values = new object[props.Length]; + + for (int i = 0; i < props.Length; i++) + { + values[i] = props[i].GetValue(item, null); + } + + tb.Rows.Add(values); + } + + return tb; + } + + /// + /// model转换DataTable + /// + /// + /// + /// + public DataTable ModelToDataTable(T items) + { + var tb = new DataTable(typeof(T).Name); + + PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo prop in props) + { + Type t = GetCoreType(prop.PropertyType); + tb.Columns.Add(prop.Name, t); + } + + + var values = new object[props.Length]; + + for (int i = 0; i < props.Length; i++) + { + values[i] = props[i].GetValue(items, null); + } + + tb.Rows.Add(values); + + + return tb; + } + + /// + /// Determine of specified type is nullable + /// + public static bool IsNullable(Type t) + { + return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)); + } + + /// + /// Return underlying type if type is Nullable otherwise return the type + /// + public static Type GetCoreType(Type t) + { + if (t != null && IsNullable(t)) + { + if (!t.IsValueType) + { + return t; + } + else + { + return Nullable.GetUnderlyingType(t); + } + } + else + { + return t; + } + } + + /// + /// DataTable转换泛型List + /// + /// + /// + public static List DataTableToList(DataTable dt) + { + // 定义集合 + List ts = new List(); + + // 获得此模型的类型 + Type type = typeof(T); + string tempName = ""; + foreach (DataRow dr in dt.Rows) + { + T t = new T(); + // 获得此模型的公共属性 + PropertyInfo[] propertys = t.GetType().GetProperties(); + foreach (PropertyInfo pi in propertys) + { + tempName = pi.Name; // 检查DataTable是否包含此列 + + if (dt.Columns.Contains(tempName)) + { + // 判断此属性是否有Setter + if (!pi.CanWrite) continue; + + object value = dr[tempName]; + if (value != DBNull.Value) + pi.SetValue(t, value, null); + } + } + ts.Add(t); + } + return ts; + } + + + /// + /// DataTable转Model + /// + /// + /// + public static T DataTableToModel(DataTable dt) + { + // 定义实体 + T t = new T(); + + // 获得此模型的类型 + Type type = typeof(T); + string tempName = ""; + + foreach (DataRow dr in dt.Rows) + { + + // 获得此模型的公共属性 + PropertyInfo[] propertys = t.GetType().GetProperties(); + foreach (PropertyInfo pi in propertys) + { + tempName = pi.Name; // 检查DataTable是否包含此列 + + if (dt.Columns.Contains(tempName)) + { + // 判断此属性是否有Setter + if (!pi.CanWrite) continue; + + object value = dr[tempName]; + if (value != DBNull.Value) + pi.SetValue(t, value, null); + } + } + break; + } + return t; + } + } +} diff --git a/HappyReading/DAL/SQLiteDBHelper.cs b/HappyReading/DAL/SQLiteDBHelper.cs new file mode 100644 index 0000000..96f43d3 --- /dev/null +++ b/HappyReading/DAL/SQLiteDBHelper.cs @@ -0,0 +1,155 @@ +using System; +using System.Data; +using System.Data.Common; +using System.Data.SQLite; + +namespace HappyReading.DAL +{ + /// + /// 说明:这是一个针对System.Data.SQLite的数据库常规操作封装的通用类。 + /// 作者:zhoufoxcn(周公) + /// 日期:2010-04-01 + /// Blog:http://zhoufoxcn.blog.51cto.com or http://blog.csdn.net/zhoufoxcn + /// Version:0.1 + /// + public class SQLiteDBHelper + { + private static string connectionString = "Data Source=" + AppDomain.CurrentDomain.BaseDirectory + @"db\HappyReading.db"; + /// + /// 构造函数 + /// + public SQLiteDBHelper() + { + + } + + + + /// + /// 创建SQLite数据库文件 + /// + /// 要创建的SQLite数据库文件路径 + public static void CreateDB(string dbPath) + { + using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath)) + { + connection.Open(); + using (SQLiteCommand command = new SQLiteCommand(connection)) + { + command.CommandText = "CREATE TABLE Demo(id integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE)"; + command.ExecuteNonQuery(); + command.CommandText = "DROP TABLE Demo"; + command.ExecuteNonQuery(); + } + } + } + /// + /// 对SQLite数据库执行增删改操作,返回受影响的行数。 + /// + /// 要执行的增删改的SQL语句 + /// 执行增删改语句所需要的参数,参数必须以它们在SQL语句中的顺序为准 + /// + public static int ExecuteNonQuery(string sql, SQLiteParameter[] parameters) + { + int affectedRows = 0; + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + connection.Open(); + using (DbTransaction transaction = connection.BeginTransaction()) + { + using (SQLiteCommand command = new SQLiteCommand(connection)) + { + command.CommandText = sql; + if (parameters != null) + { + command.Parameters.AddRange(parameters); + } + affectedRows = command.ExecuteNonQuery(); + } + transaction.Commit(); + } + } + return affectedRows; + } + /// + /// 执行一个查询语句,返回一个关联的SQLiteDataReader实例 + /// + /// 要执行的查询语句 + /// 执行SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准 + /// + public SQLiteDataReader ExecuteReader(string sql, SQLiteParameter[] parameters) + { + SQLiteConnection connection = new SQLiteConnection(connectionString); + SQLiteCommand command = new SQLiteCommand(sql, connection); + if (parameters != null) + { + command.Parameters.AddRange(parameters); + } + connection.Open(); + return command.ExecuteReader(CommandBehavior.CloseConnection); + } + /// + /// 执行一个查询语句,返回一个包含查询结果的DataTable + /// + /// 要执行的查询语句 + /// 执行SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准 + /// + public static DataTable ExecuteDataTable(string sql, SQLiteParameter[] parameters) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + using (SQLiteCommand command = new SQLiteCommand(sql, connection)) + { + if (parameters != null) + { + command.Parameters.AddRange(parameters); + } + SQLiteDataAdapter adapter = new SQLiteDataAdapter(command); + DataTable data = new DataTable(); + adapter.Fill(data); + return data; + } + } + + } + + /// + /// 执行一个查询语句,返回查询结果的第一行第一列 + /// + /// 要执行的查询语句 + /// 执行SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准 + /// + public static Object ExecuteScalar(string sql, string name) + { + + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + using (SQLiteCommand command = new SQLiteCommand(sql, connection)) + { + SQLiteDataAdapter adapter = new SQLiteDataAdapter(command); + DataTable data = new DataTable(); + adapter.Fill(data); + return data.Rows[0][name]; + } + } + + + + } + /// + /// 查询数据库中的所有数据类型信息 + /// + /// + public static DataTable GetSchema() + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + connection.Open(); + DataTable data = connection.GetSchema("TABLES"); + connection.Close(); + + return data; + } + } + } +} diff --git a/HappyReading/DAL/TempData.cs b/HappyReading/DAL/TempData.cs new file mode 100644 index 0000000..d55e8ff --- /dev/null +++ b/HappyReading/DAL/TempData.cs @@ -0,0 +1,97 @@ +using HappyReading.BLL; +using HappyReading.Model; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace HappyReading.DAL +{ + class TempData + { + + /// + /// 全部书源 + /// + private static List BookSourceS = null; + + + /// + /// 写入全部书源 + /// + /// + public static void SetBookSourceS(List bookSources) + { + BookSourceS = bookSources; + } + + /// + /// 更新全部书源 + /// + public static void UpdateBookSourceS() + { + BookSourceS = DataFetch.GetBookSources(); + } + + + /// + /// 初始化 + /// + public static void Initialization() + { + if (BookSourceS == null) + { + BookSourceS = DataFetch.GetBookSources(); + } + } + + + /// + /// 获取全部书源 + /// + /// + public static List GetBookSourceS() + { + Initialization(); + return BookSourceS; + } + + + /// + /// 存放网站编码的地方 + /// + public static Dictionary UrlCode = new Dictionary(); + + + /// + /// 获取网站编码 + /// + /// + /// + public static string GetUrlCode(string url) + { + try + { + //把网址分割,取出域名部分 + string[] Urls = url.Split(new string[] { "://", "/" }, StringSplitOptions.RemoveEmptyEntries); + if (UrlCode.ContainsKey(Urls[1])) + { + return UrlCode[Urls[1]]; + } + else + { + UrlCode[Urls[1]] = GetHtml.GetCode(url); + return UrlCode[Urls[1]]; + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + //Exception ex + Tool.TextAdditional(ex.Message); + return ""; + } + } + } +} diff --git a/HappyReading/HappyReading.csproj b/HappyReading/HappyReading.csproj new file mode 100644 index 0000000..8dae1d9 --- /dev/null +++ b/HappyReading/HappyReading.csproj @@ -0,0 +1,175 @@ + + + + + Debug + AnyCPU + {A7AAEB8A-9CDA-485D-88A5-15208889EDDA} + WinExe + HappyReading + HappyReading + v4.5 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + favicon.ico + + + + ..\packages\ControlzEx.3.0.2.4\lib\net45\ControlzEx.dll + + + ..\packages\MahApps.Metro.1.6.5\lib\net45\MahApps.Metro.dll + + + False + ..\..\..\项目文件夹\Json120r1\Bin\net45\Newtonsoft.Json.dll + + + + + + False + bin\Debug\System.Data.SQLite.dll + + + False + bin\Debug\System.Data.SQLite.Linq.dll + + + + + + + ..\packages\ControlzEx.3.0.2.4\lib\net45\System.Windows.Interactivity.dll + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + + + + + + + + + + + + + BookSourceAdd.xaml + + + DetailsPage.xaml + + + ReadingPage.xaml + + + Tips.xaml + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + + + MainWindow.xaml + Code + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + + + + + \ No newline at end of file diff --git a/HappyReading/MainWindow.xaml b/HappyReading/MainWindow.xaml new file mode 100644 index 0000000..bb6fec3 --- /dev/null +++ b/HappyReading/MainWindow.xaml @@ -0,0 +1,201 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 全部 + + + + +