Skip to content

Commit 688508e

Browse files
committed
Start Logging
1 parent ff60fb2 commit 688508e

9 files changed

+106
-69
lines changed

BookStore/BookStore.csproj

+3-3
Original file line numberDiff line numberDiff line change
@@ -318,13 +318,13 @@
318318
<Content Include="Content\Admin.css.map">
319319
<DependentUpon>Admin.css</DependentUpon>
320320
</Content>
321+
<Content Include="log.txt">
322+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
323+
</Content>
321324
<Content Include="Scripts\AddField.js" />
322325
<Content Include="Scripts\bootstrap.min.js.map">
323326
<DependentUpon>bootstrap.min.js</DependentUpon>
324327
</Content>
325-
<Content Include="NLog.config">
326-
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
327-
</Content>
328328
<None Include="Scripts\jquery-1.9.1.intellisense.js" />
329329
<Content Include="Scripts\bootstrap.js" />
330330
<Content Include="Scripts\bootstrap.min.js" />

BookStore/Controllers/AccountController.cs

+2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ public class AccountController : Controller
1616
{
1717
private IUserService _userService;
1818
private IRoleService _roleService;
19+
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
20+
1921

2022
public AccountController(IUserService user_service, IRoleService role_service)
2123
{

BookStore/Controllers/AdminController.cs

+11-4
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ namespace BookStore.Controllers
1717
[Authorize(Roles = "admin")]
1818
public class AdminController : Controller
1919
{
20-
public static Logger Log;
20+
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
21+
2122
public AdminController()
2223
{
2324

@@ -63,7 +64,9 @@ public ViewResult Create()
6364
[HttpPost]
6465
public ActionResult FindBookImage(string title, string lastName, string firstName, int bookId)
6566
{
66-
IList<SearchResult> searchResults = SearchResult.getSearch(title + " " + lastName + " " + firstName, "&searchType=image");
67+
string query =title + " " + lastName + " " + firstName ;
68+
logger.Info(query);
69+
IList < SearchResult > searchResults = SearchResult.GetSearch(query,"&searchType=image");
6770
ViewData["BookID"] = bookId;
6871
return PartialView(searchResults.Select(x => x.link));
6972
}
@@ -96,8 +99,8 @@ public string CopyImageToHost(string imageUrl, int bookId)
9699
public ActionResult FindBookAnnotation(string title, string lastName, string firstName, int bookId)
97100
{
98101
string query = title + " " + lastName + " " + firstName + " " + "litres";
99-
//Log.Info(query);
100-
List<string> links = SearchResult.getSearch(query).Select(x => x.link).ToList();
102+
logger.Info(query);
103+
List<string> links = SearchResult.GetSearch(query).Select(x => x.link).ToList();
101104
ViewData["BookID"] = bookId;
102105
return PartialView(SearchResult.GetInnerText(links));
103106
}
@@ -108,6 +111,7 @@ public ActionResult Create(Book book)
108111
if (ModelState.IsValid)
109112
{
110113
_bookService.Create(book);
114+
logger.Info(book.Title+" created");
111115
TempData["message"] = string.Format("{0} has been saved", book.Title);
112116
return RedirectToAction("Edit", new { bookID = book.Book_ID });
113117
}
@@ -120,6 +124,7 @@ public ActionResult Edit(Book book)
120124
if (ModelState.IsValid)
121125
{
122126
_bookService.Save(book);
127+
logger.Info(book.Title + " edited");
123128
TempData["message"] = string.Format("{0} has been saved", book.Title);
124129
return RedirectToAction("Index");
125130
}
@@ -130,8 +135,10 @@ public ActionResult Edit(Book book)
130135
public ActionResult Delete(int bookId)
131136
{
132137
Book deletedBook = _bookService.Delete(bookId);
138+
133139
if (deletedBook != null)
134140
{
141+
logger.Info(deletedBook.Title + " dletedted");
135142
TempData["message"] = string.Format("{0} was deleted", deletedBook.Title);
136143
}
137144
return RedirectToAction("Index");

BookStore/Controllers/BookController.cs

+8-5
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ public class BookController : Controller
1818
private readonly IBookService _bookService;
1919
private IGenreService _genreService;
2020
public int PageSize = 10;
21+
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
22+
2123
public BookController(IBookService book_service, IGenreService genre_service)
2224
{
2325
_bookService = book_service;
@@ -31,13 +33,13 @@ public ViewResult BookDetails(int bookId)
3133
return View(_bookService.GetById(bookId));
3234
}
3335

34-
public ICollection<Book> PaginateBooks(IQueryable<Book> books,int page)
36+
public ICollection<Book> PaginateBooks(List<Book> books, int page)
3537
{
3638
return books.Skip((page - 1)*PageSize).Take(PageSize).ToList();
3739
}
3840
public ViewResult ListByTag(int tagId, int page = 1)
3941
{
40-
IQueryable<Book> books = _bookService.GetBooksByTag(tagId);
42+
List<Book> books = _bookService.GetBooksByTag(tagId).ToList();
4143
BookListViewModel model = new BookListViewModel
4244
{
4345
Books = PaginateBooks(books,page),
@@ -50,7 +52,7 @@ public ViewResult ListByTag(int tagId, int page = 1)
5052
}
5153
public ViewResult ListByLetter(string selectedLetter, int page = 1)
5254
{
53-
IQueryable<Book> books = _bookService.GetBooksByLetter(selectedLetter);
55+
List<Book> books = _bookService.GetBooksByLetter(selectedLetter).ToList();
5456
BookListViewModel model = new BookListViewModel
5557
{
5658
Books = PaginateBooks(books, page),
@@ -62,7 +64,8 @@ public ViewResult ListByLetter(string selectedLetter, int page = 1)
6264
}
6365
public ViewResult ListByGenre(string genre, int page = 1)
6466
{
65-
IQueryable<Book> books = _bookService.GetBooksByGenre(genre);
67+
List<Book> books = _bookService.GetBooksByGenre(genre).ToList();
68+
logger.Info(books);
6669
BookListViewModel model = new BookListViewModel
6770
{
6871
Books = PaginateBooks(books, page),
@@ -77,7 +80,7 @@ public ViewResult List(int page = 1)
7780
List<Book> books = _bookService.GetAll().ToList();
7881
BookListViewModel model = new BookListViewModel
7982
{
80-
Books = PaginateBooks(books.AsQueryable(), page),
83+
Books = PaginateBooks(books, page),
8184
PagingInfo = new PagingInfo(page, PageSize, books.Count()),
8285
};
8386
ViewBag.Action = "List";

BookStore/Global.asax.cs

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.IO;
34
using System.Linq;
45
using System.Web;
56
using System.Web.Http;
@@ -19,6 +20,8 @@ namespace BookStore
1920

2021
public class MvcApplication : System.Web.HttpApplication
2122
{
23+
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
24+
2225
protected void Application_Start()
2326
{
2427
AreaRegistration.RegisterAllAreas();
@@ -33,7 +36,9 @@ protected void Application_Start()
3336
controllerFactory.InjectRoleProvider(Roles.Provider);
3437
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
3538
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
36-
39+
// log4net.Config.XmlConfigurator.Configure();
40+
log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
41+
3742
}
3843
}
3944
}

BookStore/Models/SearchResult.cs

+46-25
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@
88
using System.Net;
99
//using System.Net;
1010
using System.Web;
11+
using NLog;
1112

1213
namespace BookStore.Models
1314
{
1415
public class SearchResult
1516
{
16-
private static HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
17+
private static HtmlDocument doc = new HtmlDocument();
18+
readonly static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
1719

1820
public string Title { get; set; }
1921
public string htmlTitle { get; set; }
@@ -26,31 +28,31 @@ public static List<string> GetInnerText(List<string> links)
2628
{
2729
if (link.Contains("livelib"))
2830
{
29-
doc.LoadHtml(getRequest(link));
31+
doc.LoadHtml(GetRequest(link));
3032
c = doc.DocumentNode.SelectSingleNode("//p[@itemprop='about']");
31-
if (c != null) result.Add(HttpUtility.HtmlDecode(c.InnerText));
33+
if (c != null) result.Add(HttpUtility.HtmlDecode(c.InnerText));
3234
}
3335
else if (link.Contains("aldebaran"))
3436
{
35-
doc.LoadHtml(getRequest(link));
37+
doc.LoadHtml(GetRequest(link));
3638
c = doc.DocumentNode.SelectSingleNode("//div[@class='annotation clearfix']");
37-
if (c != null) result.Add(HttpUtility.HtmlDecode(c.FirstChild.InnerText));
39+
if (c != null) result.Add(HttpUtility.HtmlDecode(c.FirstChild.InnerText));
3840
}
3941
else if (link.Contains("loveread"))
4042
{
41-
doc.LoadHtml(getRequest(link));
43+
doc.LoadHtml(GetRequest(link));
4244
c = doc.DocumentNode.SelectSingleNode("//p[@class='span_str']");
4345
if (c != null) result.Add(HttpUtility.HtmlDecode(c.InnerText));
4446
}
4547
else if (link.Contains("e-reading.club"))
4648
{
47-
doc.LoadHtml(getRequest(link));
49+
doc.LoadHtml(GetRequest(link));
4850
c = doc.DocumentNode.SelectSingleNode("//span[@itemprop='description']");
4951
if (c != null) result.Add(HttpUtility.HtmlDecode(c.InnerText));
5052
}
5153
else if (link.Contains("litres"))
5254
{
53-
doc.LoadHtml(getRequest(link));
55+
doc.LoadHtml(GetRequest(link));
5456
c = doc.DocumentNode.SelectSingleNode("//div[@itemprop='description']");
5557
if (c != null)
5658
{
@@ -62,46 +64,65 @@ public static List<string> GetInnerText(List<string> links)
6264
}
6365
else if (link.Contains("mybook"))
6466
{
65-
doc.LoadHtml(getRequest(link));
67+
doc.LoadHtml(GetRequest(link));
6668
c = doc.DocumentNode.SelectSingleNode("//div[@class='definition-section']");
6769
if (c != null) result.Add(HttpUtility.HtmlDecode(c.FirstChild.InnerText));
6870
}
6971
}
7072

7173
return result;
7274
}
73-
public static string getRequest(string url)
75+
public static string GetRequest(string url)
7476
{
75-
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
76-
httpWebRequest.AllowAutoRedirect = false;//Запрещаем автоматический редирект
77-
using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
77+
try
7878
{
79-
using (var stream = httpWebResponse.GetResponseStream())
79+
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
80+
httpWebRequest.AllowAutoRedirect = false;//Запрещаем автоматический редирект
81+
using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
8082
{
81-
using (var reader = new StreamReader(stream))
83+
using (var stream = httpWebResponse.GetResponseStream())
8284
{
83-
return reader.ReadToEnd();
85+
using (var reader = new StreamReader(stream))
86+
{
87+
return reader.ReadToEnd();
88+
}
8489
}
8590
}
8691
}
92+
catch (WebException ex)
93+
{
94+
95+
logger.Error("You exceeded limit", ex);
96+
return null;
97+
//throw;
98+
}
99+
87100
}
88-
public static IList<SearchResult> getSearch(string searchText, string cfg = "")
101+
public static IList<SearchResult> GetSearch(string searchText, string cfg = "")
89102
{
90103
string key = "AIzaSyBzcXSZrtK15FFCX8v_Ob-Hcxnc-cVHc-Y";
91104
string cx = "015577388163479462430:16-o3xadmg4";
92105
//string key = "AIzaSyAmaV0ew89918tcxHYXbM0VsVM-G6wRKwY";
93106
//string cx = "003508446447238917805:tgox65vdhtw";
94-
string google = "https://www.googleapis.com/customsearch/v1?key=" + key + "&cx=" + cx + "&q=" + searchText + "&alt=json" + cfg;
95-
JObject googleSearch = JObject.Parse(getRequest(google));
96-
List<JToken> results = googleSearch["items"].Children().ToList();
97107
IList<SearchResult> searchResults = new List<SearchResult>();
98-
foreach (JToken result in results)
108+
string google = "https://www.googleapis.com/customsearch/v1?key=" + key + "&cx=" + cx + "&q=" + searchText + "&alt=json" + cfg;
109+
try
110+
{
111+
JObject googleSearch = JObject.Parse(GetRequest(google));
112+
List<JToken> results = googleSearch["items"].Children().ToList();
113+
foreach (JToken result in results)
114+
{
115+
SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
116+
searchResults.Add(searchResult);
117+
}
118+
return searchResults;
119+
}
120+
catch (Exception)
99121
{
100-
SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
101-
searchResults.Add(searchResult);
122+
return searchResults;
123+
124+
//throw;
102125
}
103-
return searchResults;
104126
}
105-
106127
}
107128
}

BookStore/NLog.config

-30
This file was deleted.

BookStore/Web.config

+29-1
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,38 @@
66
<configuration>
77
<configSections>
88
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
9+
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
910

1011
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
1112
</configSections>
12-
13+
14+
<log4net debug="true">
15+
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
16+
<file value="logs\log.txt" />
17+
<appendToFile value="true" />
18+
<rollingStyle value="Size" />
19+
<maxSizeRollBackups value="10" />
20+
<maximumFileSize value="10MB" />
21+
<staticLogFileName value="true" />
22+
<layout type="log4net.Layout.PatternLayout">
23+
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
24+
</layout>
25+
</appender>
26+
<root>
27+
<level value="ALL" />
28+
<level value="DEBUG" />
29+
<appender-ref ref="RollingLogFileAppender" />
30+
</root>
31+
<logger name="PerformanceLogger">
32+
<level value="ALL" />
33+
<appender-ref ref="PerformanceFileAppender" />
34+
</logger>
35+
<logger name="ErrorLogger">
36+
<level value="ALL" />
37+
<appender-ref ref="ErrorFileAppender" />
38+
</logger>
39+
</log4net>
40+
1341
<connectionStrings>
1442
<add name="EfDbContext" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=Book; Integrated Security=True" providerName="System.Data.SqlClient" />
1543
</connectionStrings>

BookStore/log.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
INFO 2015-04-09 08:21:45,867 111336ms AdminController FindBookAnnotation - ��� � ��������� ����� ����� litres

0 commit comments

Comments
 (0)