var data = db.Products.Include("Repositories");
var values = new List<ProductWithRepoDTO>();
foreach(var record in data)
{
var reposArray = record.Repositories.Select(x=>x.Name).ToArray();
var reposString = string.Join(",", reposArray);
values.Add(new ProductWithRepoDTO
{
Id = record.Id,
Name = record.Name,
Cound = record.Count,
Price = record.Price,
Repository = reposString
});
}
//дальше работать с values
public partial class Form1 : Form
{
private readonly LoginViewModel viewModel;
public Form1()
{
InitializeComponent();
viewModel = new LoginViewModel();
txtUserName.DataBindings.Add(new Binding("Text", viewModel, "UserName", false, DataSourceUpdateMode.OnPropertyChanged));
txtPassword.DataBindings.Add(new Binding("Text", viewModel, "Password", false, DataSourceUpdateMode.OnPropertyChanged));
}
private void buttonSave_Click(object sender, EventArgs e)
{
var file = GetFilePath();
using (var buffer = File.OpenWrite(file))
{
var formatter = new BinaryFormatter();
formatter.Serialize(buffer, viewModel);
}
}
private void buttonLoad_Click(object sender, EventArgs e)
{
var model = LoadContent() as LoginViewModel;
if (model != null)
{
viewModel.Password = model.Password;
viewModel.UserName = model.UserName;
}
}
private static object LoadContent()
{
var file = GetFilePath();
if (!File.Exists(file))
return null;
using (var buffer = File.OpenRead(file))
{
var formatter = new BinaryFormatter();
try
{
return formatter.Deserialize(buffer);
}
catch
{
//TODO Add error handling
return null;
}
}
}
private static string GetFilePath()
{
var directory = Path.GetDirectoryName(typeof(Form1).Assembly.Location);
return Path.Combine(directory, "store.txt");
}
}
[Serializable]
public class LoginViewModel : INotifyPropertyChanged
{
private string _userName;
private string _password;
public string UserName
{
get { return _userName; }
set
{
_userName = value;
NotifyPropertyChanged(nameof(UserName));
}
}
public string Password
{
get { return _password; }
set
{
_password = value;
NotifyPropertyChanged(nameof(Password));
}
}
private void NotifyPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
}
SELECT
@day:=DATE_FORMAT(t.`timestamp`, '%Y-%m-%d') `date`
, @success:= (SELECT COUNT(id) FROM `tests` WHERE `totalQuestions` = `correctAnswers` AND DATE_FORMAT(`timestamp`, '%Y-%m-%d') = @day) `success`
, @total:= (SELECT COUNT(id) FROM `tests` WHERE DATE_FORMAT(`timestamp`, '%Y-%m-%d') = @day) `total`
, @success* 100 / @total `percent`
FROM `tests` t
GROUP BY DATE_FORMAT(`timestamp`, '%Y-%m-%d')
@RequestMapping(value = "/", method = RequestMethod.GET)
public String list(Model uiModel) {
List<HotelAudit> contacts = HotelService.findAll();
uiModel.addAttribute("contacts", contacts);
return "list";
}
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/j_spring_security_logout</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<beans:bean id="tokenPersistRepo"
class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
<beans:property name="dataSource" ref="dataSource"/>
</beans:bean>
<beans:bean id="nonAjaxRequestMatcher" class="org.whatever.NonAjaxRequestMatcher"/>
<beans:bean id="loginUrlAuthenticationEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:constructor-arg value="/login"/>
</beans:bean>
<beans:bean id="ajaxAuthenticationEntryPoint"
class="org.springframework.security.web.authentication.HttpStatusEntryPoint">
<beans:constructor-arg name="httpStatus"
value="#{T(org.springframework.http.HttpStatus).UNAUTHORIZED}"/>
</beans:bean>
<beans:bean id="authenticationRequestCache"
class="org.springframework.security.web.savedrequest.HttpSessionRequestCache">
<beans:property name="requestMatcher" ref="nonAjaxRequestMatcher"/>
</beans:bean>
<beans:bean id="authenticationEntryPoint"
class="org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint">
<beans:constructor-arg>
<beans:map>
<beans:entry key-ref="nonAjaxRequestMatcher" value-ref="loginUrlAuthenticationEntryPoint"/>
</beans:map>
</beans:constructor-arg>
<beans:property name="defaultEntryPoint" ref="ajaxAuthenticationEntryPoint"/>
</beans:bean>
<http entry-point-ref="authenticationEntryPoint" use-expressions="true">
<request-cache ref="authenticationRequestCache"/>
<headers>
<frame-options disabled="true"/>
</headers>
<intercept-url pattern="/backend/roles/**" access="hasAnyRole('ROLE_ADMINISTRATOR')"/>
<intercept-url pattern="/backend/**" access="hasAnyRole('ROLE_ADMINISTRATOR', 'ROLE_SYS')"/>
<intercept-url pattern="/registries/**" access="hasAnyRole('ROLE_ADMINISTRATOR', 'ROLE_SYS', 'ROLE_REGISTRY')"/>
<intercept-url pattern="/registries" access="hasAnyRole('ROLE_ADMINISTRATOR', 'ROLE_SYS', 'ROLE_REGISTRY')"/>
<intercept-url pattern="/login/**" access="permitAll"/>
<intercept-url pattern="/logout/**" access="permitAll"/>
<intercept-url pattern="/resources/**" access="permitAll"/>
<intercept-url pattern="/bundles/**" access="permitAll"/>
<intercept-url pattern="/jawr/**" access="permitAll"/>
<intercept-url pattern="/error/**" access="permitAll"/>
<access-denied-handler error-page="/403"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login login-page="/login" default-target-url="/"
authentication-failure-url="/login?error" username-parameter="username"
password-parameter="password"/>
<logout logout-success-url="/" logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID,remember-me"/>
<remember-me
key="${app.remember-me-key}"
remember-me-parameter="remember-me"
remember-me-cookie="remember-me"
token-validity-seconds="86400"
token-repository-ref="tokenPersistRepo"/>
<csrf/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="usersManager">
<password-encoder hash="bcrypt"/>
</authentication-provider>
</authentication-manager>
</beans:beans>
@RequestMapping(value = {"/url/to/profileAction/{id}"}, method = RequestMethod.GET)
public ModelAndView profileAction(@PathVariable("id") Long id) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("profile");
UserDTO data = getUserDTOsService().getById(id);
if (data != null) {
modelAndView.getModel().put("data", data);
return modelAndView;
}
return "redirect:/";/*ну или бросить исключение, что нет пользователя*/
}
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.7</version>
</dependency>
// check if user is login
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if ((!(auth instanceof AnonymousAuthenticationToken)) && auth != null) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
if (userDetail != null) {
model.addObject("username", userDetail.getUsername());
} else {
model.addObject("username", "");
}
}
,<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="usersManager">
<password-encoder hash="bcrypt"/>
</authentication-provider>
</authentication-manager>
<bean id="usersManager" class="org.whatever.impl.UsersServiceImpl">
<property name="usersDAO" ref="usersDAO"/>
<property name="languageDao" ref="languagesDAO"/>
<property name="roleDAO" ref="roleDAO"/>
<property name="usersViewDAO" ref="usersViewDAO"/>
</bean>
package org.whatever.impl;
/*импорты убрал */
/* интерфейс UsersService наследует org.springframework.security.core.userdetails.UserDetailsService */
public class UsersServiceImpl extends ServiceBase implements UsersService {
@Autowired
private UsersDAO usersDAO;
public void setUsersViewDAO(UsersViewDAO usersViewDAO) {
this.usersViewDAO = usersViewDAO;
}
public UsersDAO getUsersDAO() {
return usersDAO;
}
/*сократил код*/
/**
* Детали по пользователю, полученному из базы
*/
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
User userFromDb = this.getUsersDAO().getUserByLogin(login);
if (userFromDb != null) {
return new org.whatever.UserView(userFromDb); /*применяет org.springframework.security.core.userdetails.UserDetails*/
}
String result = new Formatter().format("User with login %s not found", login).toString();
throw new UsernameNotFoundException(result);
}
}