public UserRepository(UnitOfWorkManager unitOfWorkManager, ICurrentUser currentUser) : base(unitOfWorkManager, currentUser) { }
public UnitOfWorkManager() { Current = this; }
private async void btn_Out_Click(object sender, RoutedEventArgs e) { #region 移到接口实现 接口实现中无法调用收费界面 if (_outEntranceDto == null) { await this.ShowMessageAsync("提示", "未找到出入口信息"); return; } var carNumber = txt_OutCarNumber.Text; if (carNumber.IsNullOrEmpty()) { await this.ShowMessageAsync("提示", "车牌号不允许为空!"); return; } using (var unitOfWork = UnitOfWorkManager.Begin()) { var isCarIn = _vehicleFlow.IsCarIn(_outEntranceDto.ParkLevel.Park.Id, carNumber); if (isCarIn.IsCarIn) { var user = _carNumberPermission.GetUser(_outEntranceDto.ParkLevel.Park.Id, carNumber); if (user != null) { var typeId = user.CarPorts.FirstOrDefault()?.CarPortTypeId; var carType = _repositoryCarType.GetAll().FirstOrDefault(x => x.Id == (typeId.HasValue ? typeId.Value : parkBoxOptions.TempCarTypeId)); //月租车正常出场 if (carType.Category == CarType.Month) { if (!isCarIn.CarInRecord.IsMonthTempIn) { var outRcode = _vehicleFlow.CarOut(isCarIn.CarInRecord, new Parks.ParkBox.CarOutModel() { Pay = 0, InOutType = Enum.InOutTypeEnum.Artificial, OutTime = DateTime.Now }); if (outRcode != null) { parkEntrances[_outEntranceDto.Id]?.SetInfo(outRcode); } else { await this.ShowMessageAsync("提示", "出场失败!"); } } else { //月租车收费 DateTime outTime = DateTime.Now; FareRule fareRule = _repositoryFareRule.GetAll().FirstOrDefault(x => x.CarTypeId == parkBoxOptions.TempCarTypeId); var rangTimes = _repositoryRangeTime.GetAllIncluding(x => x.FareRule).Where(x => x.FareRuleId == fareRule.Id).ToList(); fareRule.TimeRangeList = rangTimes; if (isCarIn.CarInRecord.TempConvertMonthTime.HasValue) { outTime = isCarIn.CarInRecord.TempConvertMonthTime.Value; } var receivable = fareRule.CalculateFees(isCarIn.CarInRecord.InTime, outTime, 0); var carOutModel = new CarOutModel() { CarInRecord = isCarIn.CarInRecord, InOutType = Enum.InOutTypeEnum.Artificial, OutTime = DateTime.Now, Receivable = receivable, ParkId = _outEntranceDto.ParkLevel.Park.Id }; if (parkBoxOptions.IsZeroMoneyOut && receivable == 0) //收费为0 直接放行 { var outRcode = _vehicleFlow.CarOut(isCarIn.CarInRecord, carOutModel); if (outRcode != null) { await parkEntrances[_outEntranceDto.Id]?.SetInfo(outRcode); await parkEntrances[_outEntranceDto.Id]?.OpenRod(); await _ledManager.SpeakAndShowText((parkEntrances[_inEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), carOutModel, OutEnum.SuccessfulPayment); //播报语音 } else { await this.ShowMessageAsync("提示", "出场失败!"); } return; } await _ledManager.SpeakAndShowText((parkEntrances[_inEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), carOutModel, OutEnum.CalculationFee); //播报语音 var tollWindow = new ChargerWindow(_ledManager, carOutModel, fareRule, receivable, _repositoryCarType, parkBoxOptions, _repositoryCarPort, _vehicleFlow, (parkEntrances[_inEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), _repositoryFareRule, _repositoryRangeTime, null); tollWindow.Init(); var isFree = tollWindow.ShowDialog(); if (isFree.HasValue && isFree.Value) { await parkEntrances[_outEntranceDto.Id]?.OpenRod(); await parkEntrances[_outEntranceDto.Id]?.SetInfo(tollWindow.CarOutRecord); await _ledManager.SpeakAndShowText((parkEntrances[_inEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), carOutModel, OutEnum.SuccessfulPayment); //播报语音 } } } else { //其他车类型 DateTime outTime = DateTime.Now; FareRule fareRule = _repositoryFareRule.GetAll().FirstOrDefault(x => x.CarTypeId == carType.Id); var rangTimes = _repositoryRangeTime.GetAllIncluding(x => x.FareRule).Where(x => x.FareRuleId == fareRule.Id).ToList(); fareRule.TimeRangeList = rangTimes; var receivable = fareRule?.CalculateFees(isCarIn.CarInRecord.InTime, outTime, 0) ?? 0; var carOutModel = new CarOutModel() { CarInRecord = isCarIn.CarInRecord, InOutType = Enum.InOutTypeEnum.Artificial, OutTime = outTime, Receivable = receivable, ParkId = _outEntranceDto.ParkLevel.Park.Id }; if (parkBoxOptions.IsZeroMoneyOut && receivable == 0) //收费为0 直接放行 { var outRcode = _vehicleFlow.CarOut(isCarIn.CarInRecord, carOutModel); if (outRcode != null) { await parkEntrances[_outEntranceDto.Id]?.SetInfo(outRcode); await parkEntrances[_outEntranceDto.Id]?.OpenRod(); await _ledManager.SpeakAndShowText((parkEntrances[_outEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), carOutModel, OutEnum.SuccessfulPayment); //播报语音 } else { await this.ShowMessageAsync("提示", "出场失败!"); } return; } await _ledManager.SpeakAndShowText((parkEntrances[_outEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), carOutModel, OutEnum.CalculationFee); //播报语音 var tollWindow = new ChargerWindow(_ledManager, carOutModel, fareRule, receivable, _repositoryCarType, parkBoxOptions, _repositoryCarPort, _vehicleFlow, (parkEntrances[_outEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), _repositoryFareRule, _repositoryRangeTime, null); tollWindow.Init(); var isFree = tollWindow.ShowDialog(); if (isFree.HasValue && isFree.Value) { await parkEntrances[_outEntranceDto.Id]?.OpenRod(); await parkEntrances[_outEntranceDto.Id]?.SetInfo(tollWindow.CarOutRecord); await _ledManager.SpeakAndShowText((parkEntrances[_outEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), carOutModel, OutEnum.SuccessfulPayment); //播报语音 } } } else { //临时车 DateTime outTime = DateTime.Now; FareRule fareRule = _repositoryFareRule.GetAll().FirstOrDefault(x => x.CarTypeId == parkBoxOptions.TempCarTypeId); var rangTimes = _repositoryRangeTime.GetAllIncluding(x => x.FareRule).Where(x => x.FareRuleId == fareRule.Id).ToList(); fareRule.TimeRangeList = rangTimes; var receivable = fareRule?.CalculateFees(isCarIn.CarInRecord.InTime, outTime, 0) ?? 0; var carOutModel = new CarOutModel() { CarInRecord = isCarIn.CarInRecord, InOutType = Enum.InOutTypeEnum.Artificial, OutTime = outTime, Receivable = receivable, ParkId = _outEntranceDto.ParkLevel.Park.Id }; if (parkBoxOptions.IsZeroMoneyOut && receivable == 0) //收费为0 直接放行 { var outRcode = _vehicleFlow.CarOut(isCarIn.CarInRecord, carOutModel); if (outRcode != null) { await parkEntrances[_outEntranceDto.Id]?.SetInfo(outRcode); await parkEntrances[_outEntranceDto.Id]?.OpenRod(); await _ledManager.SpeakAndShowText((parkEntrances[_outEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), carOutModel, OutEnum.SuccessfulPayment); //播报语音 } else { await this.ShowMessageAsync("提示", "出场失败!"); } return; } await _ledManager.SpeakAndShowText((parkEntrances[_outEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), carOutModel, OutEnum.CalculationFee); //播报语音 var tollWindow = new ChargerWindow(_ledManager, carOutModel, fareRule, receivable, _repositoryCarType, parkBoxOptions, _repositoryCarPort, _vehicleFlow, (parkEntrances[_outEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), _repositoryFareRule, _repositoryRangeTime, null); tollWindow.Init(); var isFree = tollWindow.ShowDialog(); if (isFree.HasValue && isFree.Value) { await parkEntrances[_outEntranceDto.Id]?.OpenRod(); await parkEntrances[_outEntranceDto.Id]?.SetInfo(tollWindow.CarOutRecord); await _ledManager.SpeakAndShowText((parkEntrances[_inEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), carOutModel, OutEnum.SuccessfulPayment); //播报语音 } } } else { Logger.Info(carNumber + " 无场内记录"); //无在场记录如果为月租车直接放行 否则弹出收费框 var user = _carNumberPermission.GetUser(_outEntranceDto.ParkLevel.Park.Id, carNumber); if (user != null) { var model = new Parks.ParkBox.CarOutModel() { Pay = 0, InOutType = Enum.InOutTypeEnum.Artificial, OutTime = DateTime.Now, ParkId = _outEntranceDto.ParkLevel.Park.Id }; var outRcode = _vehicleFlow.CarOut(carNumber, user, model); if (outRcode != null) { await parkEntrances[_outEntranceDto.Id]?.OpenRod(); await parkEntrances[_outEntranceDto.Id]?.SetInfo(outRcode); await _ledManager.SpeakAndShowText((parkEntrances[_outEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), model, OutEnum.SuccessfulPayment); //播报语音 } else { await this.ShowMessageAsync("提示", "出场失败!"); } return; } else { FareRule fareRule = _repositoryFareRule.GetAll().FirstOrDefault(x => x.CarTypeId == parkBoxOptions.TempCarTypeId); var rangTimes = _repositoryRangeTime.GetAllIncluding(x => x.FareRule).Where(x => x.FareRuleId == fareRule.Id).ToList(); fareRule.TimeRangeList = rangTimes; ///弹出收费框 var tollWindow = new ChargerWindow(_ledManager, carNumber, fareRule, InOutTypeEnum.Artificial, _repositoryCarType, parkBoxOptions, _repositoryCarPort, _vehicleFlow, (parkEntrances[_inEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), _repositoryFareRule, _repositoryRangeTime, null); tollWindow.Init(); var isFree = tollWindow.ShowDialog(); if (isFree.HasValue && isFree.Value) { await parkEntrances[_outEntranceDto.Id]?.OpenRod(); await parkEntrances[_outEntranceDto.Id]?.SetInfo(tollWindow.CarOutRecord); await _ledManager.SpeakAndShowText((parkEntrances[_outEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), tollWindow.CarOutModel, OutEnum.SuccessfulPayment); //播报语音 } return; } } #endregion unitOfWork.Complete(); } }
public ActionResult Create(CreatePrivateMessageViewModel createPrivateMessageViewModel) { if (!SettingsService.GetSettings().EnablePrivateMessages || LoggedOnUser.DisablePrivateMessages == true) { return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage"))); } using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { if (ModelState.IsValid) { var userTo = createPrivateMessageViewModel.UserToUsername; // first check they are not trying to message themself! if (userTo.ToLower() != LoggedOnUser.UserName.ToLower()) { // Map the view model to message var privateMessage = new PrivateMessage { UserFrom = LoggedOnUser, Subject = createPrivateMessageViewModel.Subject, Message = createPrivateMessageViewModel.Message, }; // now get the user its being sent to var memberTo = MembershipService.GetUser(userTo); // check the member if (memberTo != null) { // Check in box size // First check sender var receiverCount = _privateMessageService.GetAllReceivedByUser(memberTo.Id).Count; if (receiverCount > SettingsService.GetSettings().MaxPrivateMessagesPerMember) { ModelState.AddModelError(string.Empty, string.Format(LocalizationService.GetResourceString("PM.ReceivedItemsOverCapcity"), memberTo.UserName)); } else { // Good to go send the message! privateMessage.UserTo = memberTo; _privateMessageService.Add(privateMessage); try { TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("PM.MessageSent"), MessageType = GenericMessages.success }; unitOfWork.Commit(); // Finally send an email to the user so they know they have a new private message // As long as they have not had notifications disabled if (memberTo.DisableEmailNotifications != true) { var email = new Email { EmailFrom = SettingsService.GetSettings().NotificationReplyEmail, EmailTo = memberTo.Email, Subject = LocalizationService.GetResourceString("PM.NewPrivateMessageSubject"), NameTo = memberTo.UserName }; var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("PM.NewPrivateMessageBody"), LoggedOnUser.UserName)); email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString()); _emailService.SendMail(email); } return(RedirectToAction("Index")); } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } } } else { // Error send back to user ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("PM.UnableFindMember")); } } else { ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("PM.TalkToSelf")); } } TempData[AppConstants.MessageViewBagName] = null; return(View(createPrivateMessageViewModel)); } }
public void BeginThenEnd() { UnitOfWorkManager.Begin(); UnitOfWorkManager.End(); }
public ActionResult GoogleLogin() { var resultMessage = new GenericMessageViewModel(); Callback = Request.QueryString["callback"]; ContentTypeAlias = Request.QueryString["contentTypeAlias"]; PropertyAlias = Request.QueryString["propertyAlias"]; Feature = Request.QueryString["feature"]; if (AuthState != null) { var stateValue = Session["MVCForum_" + AuthState] as NameValueCollection; if (stateValue != null) { Callback = stateValue["Callback"]; ContentTypeAlias = stateValue["ContentTypeAlias"]; PropertyAlias = stateValue["PropertyAlias"]; Feature = stateValue["Feature"]; } } if (string.IsNullOrEmpty(SiteConstants.GooglePlusAppId) || string.IsNullOrEmpty(SiteConstants.GooglePlusAppSecret)) { resultMessage.Message = "You need to add the Google app credentials"; resultMessage.MessageType = GenericMessages.danger; } else { // Configure the OAuth client based on the options of the prevalue options var client = new GoogleOAuthClient { ClientId = SiteConstants.GooglePlusAppId, ClientSecret = SiteConstants.GooglePlusAppSecret, RedirectUri = ReturnUrl }; // Session expired? if (AuthState != null && Session["MVCForum_" + AuthState] == null) { resultMessage.Message = "Session Expired"; resultMessage.MessageType = GenericMessages.danger; } // Check whether an error response was received from Google if (AuthError != null) { resultMessage.Message = AuthErrorDescription; resultMessage.MessageType = GenericMessages.danger; if (AuthState != null) { Session.Remove("MVCForum_" + AuthState); } } // Redirect the user to the Google login dialog if (AuthCode == null) { // Generate a new unique/random state var state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["MVCForum_" + state] = new NameValueCollection { { "Callback", Callback }, { "ContentTypeAlias", ContentTypeAlias }, { "PropertyAlias", PropertyAlias }, { "Feature", Feature } }; // Declare the scope var scope = new[] { GoogleScope.OpenId, GoogleScope.Email, GoogleScope.Profile }; // Construct the authorization URL var url = client.GetAuthorizationUrl(state, scope, GoogleAccessType.Offline, GoogleApprovalPrompt.Force); // Redirect the user return(Redirect(url)); } var info = new GoogleAccessTokenResponse(); try { info = client.GetAccessTokenFromAuthorizationCode(AuthCode); } catch (Exception ex) { resultMessage.Message = string.Format("Unable to acquire access token<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.danger; } try { // Initialize the Google service var service = GoogleService.CreateFromRefreshToken(client.ClientIdFull, client.ClientSecret, info.RefreshToken); // Get information about the authenticated user var user = service.GetUserInfo(); using (UnitOfWorkManager.NewUnitOfWork()) { var userExists = MembershipService.GetUserByEmail(user.Email); if (userExists != null) { // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.UserName, true); resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.success; ShowMessage(resultMessage); RedirectToAction("Index", "Home"); } else { // Not registered already so register them var viewModel = new MemberAddViewModel { Email = user.Email, LoginType = LoginType.Google, Password = StringUtils.RandomString(8), UserName = user.Name, SocialProfileImageUrl = user.Picture, UserAccessToken = info.RefreshToken }; // Store the viewModel in TempData - Which we'll use in the register logic TempData[AppConstants.MemberRegisterViewModel] = viewModel; return(RedirectToAction("SocialLoginValidator", "Members")); } } } catch (Exception ex) { resultMessage.Message = string.Format("Unable to get user information<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.danger; } } ShowMessage(resultMessage); return(RedirectToAction("LogOn", "Members")); }
public ActionResult EditAll(Guid resourceKeyId) { using (UnitOfWorkManager.NewUnitOfWork()) { try { var resourceKey = LocalizationService.GetResourceKey(resourceKeyId); var localeResourceKeyViewModel = new LocaleResourceKeyViewModel { Id = resourceKey.Id, Name = resourceKey.Name, Notes = resourceKey.Notes, DateAdded = resourceKey.DateAdded }; var viewModel = new AllResourceValuesViewModel { ResourceKey = localeResourceKeyViewModel, ResourceValues = new Dictionary <LanguageDisplayViewModel, LocaleResourceViewModel>() }; foreach (var localeStringResource in LocalizationService.GetAllValuesForKey(resourceKeyId)) { var stringResourceViewModel = new LocaleResourceViewModel { Id = localeStringResource.Id, ResourceKeyId = localeStringResource.LocaleResourceKey.Id, LocaleResourceKey = localeStringResource.LocaleResourceKey.Name, ResourceValue = localeStringResource.ResourceValue }; var languageViewModel = new LanguageDisplayViewModel { Id = localeStringResource.Language.Id, IsDefault = localeStringResource.Language.Id == LocalizationService.CurrentLanguage.Id, Name = localeStringResource.Language.Name, LanguageCulture = localeStringResource.Language.LanguageCulture, }; if (!viewModel.ResourceValues.ContainsKey(languageViewModel)) { viewModel.ResourceValues.Add(languageViewModel, stringResourceViewModel); } else { viewModel.ResourceValues[languageViewModel] = stringResourceViewModel; } } //unitOfWork.Commit(); return(View("ListAllValues", viewModel)); } catch (Exception ex) { //unitOfWork.Rollback(); ShowError(ex.Message); LoggingService.Error(ex); return(RedirectToAction("Index")); } } }
public ActionResult Search(DialoguePage page) { var term = Request["term"]; if (!string.IsNullOrEmpty(term)) { using (UnitOfWorkManager.NewUnitOfWork()) { // Set the page index var pageIndex = AppHelpers.ReturnCurrentPagingNo(); // Returns the formatted string to search on var formattedSearchTerm = AppHelpers.ReturnSearchString(term); // Create an empty viewmodel var viewModel = new SearchViewModel(page) { Posts = new List <ViewPostViewModel>(), AllPermissionSets = new Dictionary <Category, PermissionSet>(), PageIndex = pageIndex, TotalCount = 0, Term = term }; // if there are no results from the filter return an empty search view model. if (string.IsNullOrWhiteSpace(formattedSearchTerm)) { return(View(PathHelper.GetThemeViewPath("Search"), viewModel)); } //// Get all the topics based on the search value var posts = ServiceFactory.PostService.SearchPosts(pageIndex, Settings.PostsPerPage, AppConstants.ActiveTopicsListSize, term); // Get all the categories for this topic collection var topics = posts.Select(x => x.Topic).Distinct().ToList(); var categoryIds = topics.Select(x => x.CategoryId).Distinct().ToList(); var categories = ServiceFactory.CategoryService.Get(categoryIds); // create the view model viewModel = new SearchViewModel(page) { AllPermissionSets = new Dictionary <Category, PermissionSet>(), PageIndex = pageIndex, TotalCount = posts.TotalCount, Term = formattedSearchTerm, TotalPages = posts.TotalPages }; // Current members favourites var favourites = new List <Favourite>(); if (CurrentMember != null) { favourites = ServiceFactory.FavouriteService.GetAllByMember(CurrentMember.Id); } // Get all votes for all the posts var postIds = posts.Select(x => x.Id).ToList(); var allPostVotes = ServiceFactory.VoteService.GetAllVotesForPosts(postIds); // loop through the categories and get the permissions foreach (var category in categories) { var permissionSet = ServiceFactory.PermissionService.GetPermissions(category, _membersGroups); viewModel.AllPermissionSets.Add(category, permissionSet); } // Map the posts to the posts viewmodel viewModel.Posts = new List <ViewPostViewModel>(); foreach (var post in posts) { // TODO - See if we can make this more efficient var cat = categories.FirstOrDefault(x => x.Id == post.Topic.CategoryId); var postViewModel = PostMapper.MapPostViewModel(viewModel.AllPermissionSets[cat], post, CurrentMember, Settings, post.Topic, allPostVotes, favourites, true); viewModel.Posts.Add(postViewModel); } viewModel.PageTitle = string.Concat("Search", AppHelpers.SafePlainText(term)); return(View(PathHelper.GetThemeViewPath("Search"), viewModel)); } } return(Redirect(Settings.ForumRootUrl)); }
public UserController() { UnitOfWorkManager unitOfWorkManager = new UnitOfWorkManager(); this.userManager = new ApplicationUserManager(unitOfWorkManager); }
/// <summary> /// Search through all resources for a language by page and search terms. /// Search either by key or value. /// </summary> /// <param name="searchByKey">True means serach the keys else search the values</param> /// <param name="languageId"></param> /// <param name="p"></param> /// <param name="search"></param> /// <returns></returns> private ActionResult GetLanguageResources(bool searchByKey, Guid languageId, int?p, string search) { try { using (UnitOfWorkManager.NewUnitOfWork()) { if (!ModelState.IsValid) { var errors = (from key in ModelState.Keys select ModelState[key] into state where state.Errors.Any() select state.Errors.First().ErrorMessage). ToList(); ShowErrors(errors); } else { var language = LocalizationService.Get(languageId); var pageIndex = p ?? 1; // Get all the resources or just the ones that match the search var allResources = string.IsNullOrEmpty(search) ? LocalizationService.GetAllValues(language.Id, pageIndex, AppConstants.AdminListPageSize) : searchByKey ? LocalizationService.SearchResourceKeys(language.Id, search, pageIndex, AppConstants. AdminListPageSize) : LocalizationService.SearchResourceValues(language.Id, search, pageIndex, AppConstants. AdminListPageSize); var models = allResources.Select(resource => new LocaleResourceViewModel { Id = resource.Id, ResourceKeyId = resource.LocaleResourceKey.Id, LocaleResourceKey = resource.LocaleResourceKey.Name, ResourceValue = resource.ResourceValue }).ToList(); var resourceListModel = new LanguageListResourcesViewModel { LanguageId = language.Id, LanguageName = language.Name, LocaleResources = models, PageIndex = pageIndex, TotalCount = allResources.TotalCount, Search = search }; return(View("ListValues", resourceListModel)); } } } catch (Exception ex) { ShowError(ex.Message); } // Default ie error return(RedirectToAction("Index")); }
public override Task <HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) { UnitOfWorkCompleteHandler = UnitOfWorkManager.Begin(); return(base.ExecuteAsync(controllerContext, cancellationToken)); }
protected RepositoryBase(UnitOfWorkManager uowm) : base(uowm.Orm, null, null) { uowm.Binding(this); }
public virtual async Task <ImportResult> DoImport(ImportDto importDto) { using (var unitOfWork = UnitOfWorkManager.Begin()) { var importType = ImportManager.GetImportType(importDto.Type); var result = new ImportResult(); var rowIndex = 0; foreach (var rowData in importDto.Data) { var resultDetail = new ImportResultDetail() { Row = rowIndex }; try { //先序列化再反序列化来获取对象 var serializedString = JsonConvert.SerializeObject(rowData); var obj = JsonConvert.DeserializeObject(serializedString, importType) as IImport; //调用实体的Import方法进行额外处理 await obj.Import(importDto.Parameter); resultDetail.Success = true; } catch (ImportMsgException ex) { //自定义异常用来返回验证成功但是需要返回信息的情况 resultDetail.Success = true; resultDetail.Message = ex.Message; } catch (JsonSerializationException ex) { //接收json错误,将错误字段名返回前台用于友好提示 resultDetail.Success = false; resultDetail.FieldName = ex.Path; resultDetail.Message = ex.Message; } catch (JsonReaderException ex) { //接收json错误,将错误字段名返回前台用于友好提示 resultDetail.Success = false; resultDetail.FieldName = ex.Path; resultDetail.Message = ex.Message; } catch (Exception ex) { resultDetail.Success = false; resultDetail.Message = ex.Message; } rowIndex++; result.ImportResultDetails.Add(resultDetail); } result.Success = !result.ImportResultDetails.Exists(o => !o.Success); //如果全部成功的则提交 if (result.Success) { unitOfWork.Complete(); } return(result); } }
public ActionResult GoogleSitemap() { using (UnitOfWorkManager.NewUnitOfWork()) { // Get all categoryes var allCategories = _categoryService.GetAll().ToList(); // Get all topics var allTopics = _topicService.GetAll(); // get all members profiles var members = MembershipService.GetAll(); // Sitemap holder var sitemap = new List <SitemapEntry>(); // create permissions var permissions = new Dictionary <Category, PermissionSet>(); // loop through the categories and get the permissions foreach (var category in allCategories) { var permissionSet = RoleService.GetPermissions(category, UsersRole); permissions.Add(category, permissionSet); } // ##### TOPICS // Now loop through the topics and remove any that user does not have permission for foreach (var topic in allTopics) { // Get the permissions for this topic via its parent category var permission = permissions[topic.Category]; // Add only topics user has permission to if (!permission[AppConstants.PermissionDenyAccess].IsTicked) { if (topic.Posts.Any()) { var firstOrDefault = topic.Posts.FirstOrDefault(x => x.IsTopicStarter); if (firstOrDefault != null) { var sitemapEntry = new SitemapEntry { Name = topic.Name, Url = topic.NiceUrl, LastUpdated = topic.LastPost.DateEdited }; sitemap.Add(sitemapEntry); } } } } // #### CATEGORIES foreach (var category in allCategories) { // Get the permissions for this topic via its parent category var permission = permissions[category]; // Add only topics user has permission to if (!permission[AppConstants.PermissionDenyAccess].IsTicked) { var sitemapEntry = new SitemapEntry { Name = category.Name, Url = category.NiceUrl, LastUpdated = category.DateCreated }; sitemap.Add(sitemapEntry); } } // #### MEMBERS foreach (var member in members) { var sitemapEntry = new SitemapEntry { Name = member.UserName, Url = member.NiceUrl, LastUpdated = member.CreateDate }; sitemap.Add(sitemapEntry); } return(new GoogleSitemapResult(sitemap)); } }
public ActionResult MicrosoftLogin() { var resultMessage = new GenericMessageViewModel(); var input = new { Code = AuthCode, State = AuthState, Error = new { HasError = !string.IsNullOrWhiteSpace(AuthError), Text = AuthError, ErrorDescription = AuthErrorDescription } }; // Get the prevalue options if (string.IsNullOrEmpty(Dialogue.Settings().MicrosoftAppId) || string.IsNullOrEmpty(Dialogue.Settings().MicrosoftAppSecret)) { resultMessage.Message = "You need to add the Microsoft app credentials to the web.config"; resultMessage.MessageType = GenericMessages.Danger; } else { var client = new MicrosoftOAuthClient { ClientId = Dialogue.Settings().MicrosoftAppId, ClientSecret = Dialogue.Settings().MicrosoftAppSecret, RedirectUri = ReturnUrl }; // Session expired? if (input.State != null && Session["Dialogue_" + input.State] == null) { resultMessage.Message = "Session Expired"; resultMessage.MessageType = GenericMessages.Danger; } // Check whether an error response was received from Microsoft if (input.Error.HasError) { Session.Remove("Dialogue_" + input.State); resultMessage.Message = AuthErrorDescription; resultMessage.MessageType = GenericMessages.Danger; } // Redirect the user to the Microsoft login dialog if (string.IsNullOrWhiteSpace(input.Code)) { // Generate a new unique/random state var state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["Dialogue_" + state] = "/"; // Construct the authorization URL var url = client.GetAuthorizationUrl(state, WindowsLiveScopes.Emails + WindowsLiveScopes.Birthday); // Redirect the user return(Redirect(url)); } // Exchange the authorization code for an access token MicrosoftTokenResponse accessTokenResponse; try { Session.Remove("Dialogue_" + input.State); accessTokenResponse = client.GetAccessTokenFromAuthCode(input.Code); } catch (Exception ex) { accessTokenResponse = null; resultMessage.Message = $"Unable to acquire access token<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.Danger; } try { if (string.IsNullOrEmpty(resultMessage.Message) || accessTokenResponse != null) { //MicrosoftScope debug = accessTokenResponse.Body.Scope.Items; // Initialize a new MicrosoftService so we can make calls to the API var service = MicrosoftService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken); // Make the call to the Windows Live API / endpoint var response = service.WindowsLive.GetSelf(); // Get a reference to the response body var user = response.Body; var getEmail = !string.IsNullOrWhiteSpace(user.Emails?.Preferred); if (!getEmail) { resultMessage.Message = "Unable to get email address from Microsoft account"; resultMessage.MessageType = GenericMessages.Danger; ShowMessage(resultMessage); return(RedirectToUmbracoPage(Dialogue.Settings().ForumId)); } using (UnitOfWorkManager.NewUnitOfWork()) { var userExists = AppHelpers.UmbServices().MemberService.GetByEmail(user.Emails.Preferred); if (userExists != null) { try { // Update access token userExists.Properties[AppConstants.PropMemberMicrosoftAccessToken].Value = accessTokenResponse.Body.AccessToken; AppHelpers.UmbServices().MemberService.Save(userExists); // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.Username, true); resultMessage.Message = Lang("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.Success; } catch (Exception ex) { AppHelpers.LogError(ex); } } else { // Not registered already so register them var viewModel = new RegisterViewModel { Email = user.Emails.Preferred, LoginType = LoginType.Microsoft, Password = AppHelpers.RandomString(8), UserName = user.Name, SocialProfileImageUrl = $"https://apis.live.net/v5.0/{user.Id}/picture", UserAccessToken = accessTokenResponse.Body.AccessToken }; return(RedirectToAction("MemberRegisterLogic", "DialogueRegister", viewModel)); } } } else { resultMessage.MessageType = GenericMessages.Danger; } } catch (Exception ex) { resultMessage.Message = $"Unable to get user information<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.Danger; } } ShowMessage(resultMessage); return(RedirectToUmbracoPage(Dialogue.Settings().ForumId)); }
public SysFileResponsitory(IFreeSql orm, UnitOfWorkManager uow, IUser user) : base(orm, uow, user) { }
public ActionResult EditCategory(EditCategoryViewModel categoryViewModel) { if (ModelState.IsValid) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { try { var category = _categoryService.Get(categoryViewModel.Id); category.Description = categoryViewModel.Description; category.IsLocked = categoryViewModel.IsLocked; category.ModeratePosts = categoryViewModel.ModeratePosts; category.ModerateTopics = categoryViewModel.ModerateTopics; category.Name = categoryViewModel.Name; category.SortOrder = categoryViewModel.SortOrder; category.PageTitle = categoryViewModel.PageTitle; category.MetaDescription = categoryViewModel.MetaDesc; if (categoryViewModel.ParentCategory != null) { // Set the parent category var parentCategory = _categoryService.Get(categoryViewModel.ParentCategory.Value); category.ParentCategory = parentCategory; // Append the path from the parent category SortPath(category, parentCategory); } else { // Must access property (trigger lazy-loading) before we can set it to null (Entity Framework bug!!!) var triggerEfLoad = category.ParentCategory; category.ParentCategory = null; // Also clear the path category.Path = null; } _categoryService.UpdateSlugFromName(category); TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = "Category Updated", MessageType = GenericMessages.success }; categoryViewModel = CreateEditCategoryViewModel(category); unitOfWork.Commit(); } catch (Exception ex) { LoggingService.Error(ex); unitOfWork.Rollback(); TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = "Category Update Failed", MessageType = GenericMessages.error }; } } } return(View(categoryViewModel)); }
public void Begin() { UnitOfWorkManager.Begin(); }
public ActionResult SyncCategoryPaths() { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { try { // var all categories var all = _categoryService.GetAll().ToList(); // Get all the categories var maincategories = all.Where(x => x.ParentCategory == null).ToList(); // Get the sub categories var subcategories = all.Where(x => x.ParentCategory != null).ToList(); // loop through the main categories and get all it's sub categories foreach (var maincategory in maincategories) { // get a list of sub categories, from this category var subCats = new List <Category>(); subCats = GetAllCategorySubCategories(maincategory, subcategories, subCats); // Now loop through these subcategories and set the paths var count = 1; var prevCatId = string.Empty; var prevPath = string.Empty; foreach (var cat in subCats) { if (count == 1) { // If first count just set the parent category Id cat.Path = maincategory.Id.ToString(); } else { // If past one, then we use the previous category if (string.IsNullOrEmpty(prevPath)) { cat.Path = prevCatId; } else { cat.Path = string.Concat(prevPath, ",", prevCatId); } } prevCatId = cat.Id.ToString(); prevPath = cat.Path; count++; } // Save changes on each category unitOfWork.SaveChanges(); } TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = "Category Paths Synced", MessageType = GenericMessages.success }; unitOfWork.Commit(); } catch (Exception) { unitOfWork.Rollback(); TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = "Error syncing paths", MessageType = GenericMessages.error }; } return(RedirectToAction("Index")); } }
public void BeginThenEndAfterException() { UnitOfWorkManager.Begin(); UnitOfWorkManager.End(new Exception()); }
public ActionResult DeleteUploadedFile(Guid id) { if (id != Guid.Empty) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { Topic topic = null; var message = new GenericMessageViewModel(); try { // Get the file and associated objects we'll need var uploadedFile = UploadedFileService.Get(id); var post = uploadedFile.Post; topic = post.Topic; if (_membersGroup.Name == AppConstants.AdminRoleName || uploadedFile.MemberId == CurrentMember.Id) { // Ok to delete file // Remove it from the post post.Files.Remove(uploadedFile); // store the file path as we'll need it to delete on the file system var filePath = uploadedFile.FilePath; // Now delete it UploadedFileService.Delete(uploadedFile); // And finally delete from the file system System.IO.File.Delete(Server.MapPath(filePath)); } else { message.Message = Lang("Errors.NoPermission"); message.MessageType = GenericMessages.Danger; ShowMessage(message); Redirect(topic.Url); } //Commit unitOfWork.Commit(); message.Message = Lang("Post.FileSuccessfullyDeleted"); message.MessageType = GenericMessages.Success; ShowMessage(message); return(Redirect(topic.Url)); } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); message.Message = Lang("Errors.GenericMessage"); message.MessageType = GenericMessages.Danger; ShowMessage(message); return(topic != null?Redirect(topic.Url) : ErrorToHomePage(Lang("Errors.GenericMessage"))); } } } return(ErrorToHomePage(Lang("Errors.GenericMessage"))); }
private async void btn_In_Click(object sender, RoutedEventArgs e) { if (_inEntranceDto == null) { await this.ShowMessageAsync("提示", "未找到出入口信息"); return; } var carNumber = txt_InCarNumber.Text; if (carNumber.IsNullOrEmpty()) { await this.ShowMessageAsync("提示", "车牌号不允许为空!"); return; } using (var unitOfWork = UnitOfWorkManager.Begin()) { var backList = await _repositoryBlackList.FirstOrDefaultAsync(x => x.CarNumber == carNumber); if (backList != null) { if (!parkBoxOptions.IsListView) { var cancle = await this.ShowMessageAsync("提示", "当前车辆在黑名单是否放行?", MessageDialogStyle.AffirmativeAndNegative); if (cancle == MessageDialogResult.Negative) { return; } } else { //打开实时监控画面时 Metro自带的弹窗会被盖住 采用系统弹窗 var cancle = MessageBox.Show("当前车辆在黑名单是否放行?", "提示", MessageBoxButton.OKCancel); if (cancle == MessageBoxResult.Cancel) { return; } } } var result = _carNumberPermission.CheckCarNumberPermission(carNumber, _inEntranceDto.Id); var carInModel = new Parks.ParkBox.CarInModel() { CarNumber = carNumber, Img = null, InOutType = Enum.InOutTypeEnum.Artificial, InTime = DateTime.Now, Entrance = _inEntranceDto }; if (result.IsCarIn.HasValue && !result.IsCarIn.Value) { Logger.Debug(carNumber + "no permission" + result.ToString()); if (!parkBoxOptions.IsListView) { var cancle = await this.ShowMessageAsync("当前车辆无权进入是否放行?", "提示", MessageDialogStyle.AffirmativeAndNegative); if (cancle == MessageDialogResult.Negative) { return; } } else { var cancle = MessageBox.Show("提示", "当前车辆无权进入是否放行?", MessageBoxButton.OKCancel); if (cancle == MessageBoxResult.Cancel) { return; } } } //入场时检查是否有场内记录 var isCarIn = _vehicleFlow.IsCarIn(_inEntranceDto.ParkLevel.Park.Id, carNumber); if (isCarIn.IsCarIn) { var carOutModel = new CarOutModel() { CarInRecord = isCarIn.CarInRecord, InOutType = Enum.InOutTypeEnum.Artificial, OutTime = DateTime.Now, Receivable = 0, ParkId = _inEntranceDto.ParkLevel.Park.Id, Remark = "有场内纪录,再次入场" }; _vehicleFlow.CarErrorOut(isCarIn.CarInRecord, carOutModel); } var carIn = _vehicleFlow.CarIn(carInModel, result); if (carIn != null) { await parkEntrances[_inEntranceDto.Id]?.OpenRod(); //await deviceInfoDto.Controlable.Camerable.OpenRod(); //抬杆 await _ledManager.SpeakAndShowText((parkEntrances[_inEntranceDto.Id] as ParkEntranceInfo)?.GetDeviceInfo(), carInModel, result); //播报语音 parkEntrances[_inEntranceDto.Id]?.SetInfo(carIn); } else { await this.ShowMessageAsync("提示", "入场失败"); return; } await unitOfWork.CompleteAsync(); } }
public ActionResult UploadPostFiles(AttachFileToPostViewModel attachFileToPostViewModel) { if (attachFileToPostViewModel != null && attachFileToPostViewModel.Files != null) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var message = new GenericMessageViewModel(); // First this to do is get the post var post = PostService.Get(attachFileToPostViewModel.UploadPostId); // Check we get a valid post back and have some file if (post != null && attachFileToPostViewModel.Files != null) { Topic topic = null; try { // Now get the topic topic = post.Topic; // Now get the category var category = CategoryService.Get(topic.CategoryId); // Get the permissions for this category, and check they are allowed to update and // not trying to be a sneaky mofo var permissions = PermissionService.GetPermissions(category, _membersGroup, MemberService, CategoryPermissionService); if (permissions[AppConstants.PermissionAttachFiles].IsTicked == false && CurrentMember.DisableFileUploads != true) { return(ErrorToHomePage(Lang("Errors.NoPermission"))); } // woot! User has permission and all seems ok // Before we save anything, check the user already has an upload folder and if not create one var uploadFolderPath = Server.MapPath(string.Concat(AppConstants.UploadFolderPath, CurrentMember.Id)); if (!Directory.Exists(uploadFolderPath)) { Directory.CreateDirectory(uploadFolderPath); } // Loop through each file and get the file info and save to the users folder and Db foreach (var file in attachFileToPostViewModel.Files) { if (file != null) { // If successful then upload the file var uploadResult = UploadedFileService.UploadFile(file, uploadFolderPath); if (!uploadResult.UploadSuccessful) { message.Message = uploadResult.ErrorMessage; message.MessageType = GenericMessages.Danger; ShowMessage(message); return(Redirect(topic.Url)); } // Add the filename to the database var uploadedFile = new UploadedFile { Filename = uploadResult.UploadedFileName, Post = post, MemberId = CurrentMember.Id }; UploadedFileService.Add(uploadedFile); } } //Commit unitOfWork.Commit(); // Redirect to the topic with a success message message.Message = Lang("Post.FilesUploaded"); message.MessageType = GenericMessages.Success; ShowMessage(message); return(Redirect(topic.Url)); } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); message.Message = Lang("Errors.GenericMessage"); message.MessageType = GenericMessages.Danger; ShowMessage(message); return(topic != null?Redirect(topic.Url) : ErrorToHomePage(Lang("Errors.GenericMessage"))); } } } } // Else return with error to home page return(ErrorToHomePage(Lang("Errors.GenericMessage"))); }
public ActionResult Edit(PostMemberEditViewModel userModel) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var user = MemberService.Get(userModel.MemberEditViewModel.Id); var userEditUrl = $"{Urls.GenerateUrl(Urls.UrlType.EditMember)}?id={user.Id}"; // Before we do anything DB wise, check it contains no bad links if (BannedLinkService.ContainsBannedLink(userModel.MemberEditViewModel.Signature) || BannedLinkService.ContainsBannedLink(userModel.MemberEditViewModel.Website)) { ShowMessage(new GenericMessageViewModel { Message = Lang("Errors.BannedLink"), MessageType = GenericMessages.Danger }); return(Redirect(userEditUrl)); } // Sort image out first if (userModel.MemberEditViewModel.Files != null) { // Before we save anything, check the user already has an upload folder and if not create one //var uploadFolderPath = AppHelpers.GetMemberUploadPath(CurrentMember.Id); // Loop through each file and get the file info and save to the users folder and Db var file = userModel.MemberEditViewModel.Files[0]; if (file != null) { // If successful then upload the file var memberMediFolderId = MemberService.ConfirmMemberAvatarMediaFolder(); var uploadResult = UploadedFileService.UploadFile(file, memberMediFolderId, true); if (!uploadResult.UploadSuccessful) { ShowMessage(new GenericMessageViewModel { Message = uploadResult.ErrorMessage, MessageType = GenericMessages.Danger }); return(Redirect(userEditUrl)); } // Save avatar to user user.Avatar = uploadResult.UploadedFileUrl; } } user.Signature = BannedWordService.SanitiseBannedWords(AppHelpers.ScrubHtml(userModel.MemberEditViewModel.Signature)); if (userModel.MemberEditViewModel.Twitter != null && userModel.MemberEditViewModel.Twitter.IndexOf("http", StringComparison.OrdinalIgnoreCase) <= 0) { user.Twitter = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.Twitter)); } user.Website = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.Website)); user.Comments = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.Comments)); // User is trying to update their email address, need to // check the email is not already in use if (userModel.MemberEditViewModel.Email != user.Email) { // Add get by email address var sanitisedEmail = AppHelpers.SafePlainText(userModel.MemberEditViewModel.Email); var userWithSameEmail = MemberService.GetByEmail(sanitisedEmail); //Firstly check new email isn't banned! if (BannedEmailService.EmailIsBanned(sanitisedEmail)) { unitOfWork.Rollback(); ModelState.AddModelError(string.Empty, Lang("Error.EmailIsBanned")); ShowMessage(); return(Redirect(userEditUrl)); } // If the username doesn't match this user then someone else has this email address already if (userWithSameEmail != null && userWithSameEmail.UserName != user.UserName) { unitOfWork.Rollback(); ModelState.AddModelError(string.Empty, Lang("Members.Errors.DuplicateEmail")); ShowMessage(); return(Redirect(userEditUrl)); } user.Email = sanitisedEmail; } // User is trying to change username, need to check if a user already exists // with the username they are trying to change to var changedUsername = false; var sanitisedUsername = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.UserName)); if (sanitisedUsername != user.UserName) { if (MemberService.Get(sanitisedUsername) != null) { unitOfWork.Rollback(); ModelState.AddModelError(string.Empty, Lang("Members.Errors.DuplicateUserName")); ShowMessage(); return(Redirect(userEditUrl)); } user.UserName = sanitisedUsername; changedUsername = true; } // Update Everything MemberService.SaveMember(user, changedUsername); ActivityService.ProfileUpdated(user); ShowMessage(new GenericMessageViewModel { Message = Lang("Member.ProfileUpdated"), MessageType = GenericMessages.Success }); try { // Need to save member here unitOfWork.Commit(); if (changedUsername) { // User has changed their username so need to log them in // as there new username of var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { var authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket != null) { var newFormsIdentity = new FormsIdentity(new FormsAuthenticationTicket(authTicket.Version, user.UserName, authTicket.IssueDate, authTicket.Expiration, authTicket.IsPersistent, authTicket.UserData)); var roles = authTicket.UserData.Split("|".ToCharArray()); var newGenericPrincipal = new GenericPrincipal(newFormsIdentity, roles); System.Web.HttpContext.Current.User = newGenericPrincipal; } } // sign out current user FormsAuthentication.SignOut(); // Abandon the session Session.Abandon(); // Sign in new user FormsAuthentication.SetAuthCookie(user.UserName, false); } } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); ModelState.AddModelError(string.Empty, Lang("Errors.GenericMessage")); } ShowMessage(); return(Redirect(userEditUrl)); } }
public PermissionRepo(UnitOfWorkManager unitOfWorkManager, ICurrentUser currentUser) : base(unitOfWorkManager, currentUser) { }
public LoginLogRepository(UnitOfWorkManager uowm, IUser user) : base(uowm, user) { }
public virtual async Task <TTenant> FindByIdAsync(int id) { return(await UnitOfWorkManager.WithUnitOfWorkAsync(async() => await TenantRepository.FirstOrDefaultAsync(id))); }
public UnitOfWorkAsyncInterceptor(UnitOfWorkManager unitOfWorkManager, ILogger <UnitOfWorkAsyncInterceptor> logger) { _unitOfWorkManager = unitOfWorkManager; _logger = logger; }
public virtual TTenant FindById(int id) { return(UnitOfWorkManager.WithUnitOfWork(() => TenantRepository.FirstOrDefault(id))); }
public void SetUp() { mocks = new MockRepository(); instance = mocks.DynamicMock<IUnitOfWork>(); store = mocks.DynamicMock<IUnitOfWorkStore>(); factory = mocks.DynamicMock<IUnitOfWorkFactory<NullDatabase>>(); unitOfWorkManager = mocks.Stub<UnitOfWorkManager>(); unitOfWorkManager.Add(new NullDatabase(factory, store)); }
public ActionResult Edit(MemberEditViewModel userModel) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var user = MembershipService.GetUser(userModel.Id); // Map everything in model except properties hidden on page user.Age = userModel.Age; user.Comment = userModel.Comment; user.Email = userModel.Email; user.Facebook = userModel.Facebook; user.IsApproved = userModel.IsApproved; user.IsLockedOut = userModel.IsLockedOut; user.Location = userModel.Location; user.PasswordAnswer = userModel.PasswordAnswer; user.PasswordQuestion = userModel.PasswordQuestion; user.Signature = userModel.Signature; user.Twitter = userModel.Twitter; user.UserName = userModel.UserName; user.Website = userModel.Website; user.DisableEmailNotifications = userModel.DisableEmailNotifications; user.DisablePosting = userModel.DisablePosting; user.DisablePrivateMessages = userModel.DisablePrivateMessages; // If there is a location try and save the longitude and latitude if (!string.IsNullOrEmpty(user.Location)) { try { var longLat = LocalisationUtils.GeocodeGoogle(user.Location); if (longLat != null && longLat[0] != "0") { // Got the long lat and save them to the user user.Latitude = longLat[0]; user.Longitude = longLat[1]; } } catch { LoggingService.Error("Error getting longitude and latitude from location"); } } try { unitOfWork.Commit(); ViewBag.Message = new GenericMessageViewModel { Message = "User saved", MessageType = GenericMessages.success }; } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } return(ListUsers(null, null)); } }