public async Task<ActionResult> Create(AgentViewModel vm, HttpPostedFileBase imageFile) { try { if (ModelState.IsValid) { //insert the image into the blob CloudBlockBlob imageBlob = await _repository.InsertImageBlob(imageFile); if (imageBlob != null) { vm.ImageUrl = imageBlob.Uri.ToString(); } //map viewmodel to view var agent = AutoMapperConfig.TCWMapper.Map<Agent>(vm); //now save model to db _repository.Insert(agent); await _repository.SaveAsync(); if (imageBlob != null) { //no need to call await here, because the AddMessageToQueue method already handles that _repository.AddMessageToQueue(agent.ID.ToString(), typeof(Agent).ToString()); } return RedirectToAction("Index"); } } catch (Exception ex) { //TODO: add logging } return View(vm); }
public async Task <IActionResult> UpdateProfileOfAgent(string id, AgentViewModel agentViewModel) { if (id != agentViewModel.Id) { return(NotFound()); } var agentForUpdate = await _context.Agents.FirstOrDefaultAsync(m => m.Id == id); if (agentForUpdate == null) { return(NotFound()); } agentForUpdate.Name = agentViewModel.Name; agentForUpdate.PhoneNumber = agentViewModel.PhoneNumber; agentForUpdate.LogoFileName = agentViewModel.OldLogoFileName; InputFile fileUpload = new InputFile(_hostingEnvironment); if (agentViewModel.LogoFile != null) { string uniqueFileName = null; string stringCutted = agentViewModel.LogoFile.FileName.Split('.').Last(); uniqueFileName = Guid.NewGuid().ToString() + "." + stringCutted; agentForUpdate.LogoFileName = uniqueFileName; if (agentViewModel.OldLogoFileName.ToLower() == "no file") { fileUpload.Uploadfile("files/agent_logos", agentViewModel.LogoFile, uniqueFileName); } else { fileUpload.Updatefile("files/agent_logos", agentViewModel.LogoFile, agentViewModel.OldLogoFileName, uniqueFileName); } } _context.Update(agentForUpdate); await _context.SaveChangesAsync(); return(RedirectToAction("Backpanel", "Home")); }
private void ChangeAgents(ModifyModel modifyModel, CommunityViewModel changingViewModel) { switch (modifyModel.Modification.ModificationType) { case ModificationType.Add: AddAgent(); break; case ModificationType.Remove: RemoveAgent(); break; case ModificationType.Change: RemoveAgent(); AddAgent(); break; } void AddAgent() { AgentModel agentModel = modifyModel.Modification.NewValue.AssertTypeOf <AgentModel>(); AgentViewModel viewModel = agentModel.CreateViewModel(changingViewModel); changingViewModel.AddItem(viewModel); (changingViewModel.FindItemByType <AgentViewModel>()?.AvailableItems ?? changingViewModel.FindItemByType <MessageViewModel>()?.AvailableItems)?.AvailableAgents.Add(viewModel); } void RemoveAgent() { AgentModel agentModel = modifyModel.Modification.OldValue.AssertTypeOf <AgentModel>(); AgentViewModel viewModel = (AgentViewModel)changingViewModel.FindViewItemById(agentModel.Id); changingViewModel.RemoveItem(viewModel); (changingViewModel.FindItemByType <AgentViewModel>()?.AvailableItems ?? changingViewModel.FindItemByType <MessageViewModel>()?.AvailableItems)?.AvailableAgents.Remove(viewModel); } }
public ActionResult GetAgentById(AgentViewModel aViewModel) { AgentViewModel wareViewModel = new AgentViewModel(); try { wareViewModel.BranchInfoList = _branchManager.GetBranchList(); wareViewModel.AgentInfo = _agentManager.GetAgentById(aViewModel.AgentFilter.Id); wareViewModel.AddressViewModelList.Address.ObjectId = aViewModel.AgentFilter.Id; wareViewModel.ContactViewModelList.ContactDetails.ObjectId = aViewModel.AgentFilter.Id; } catch (Exception ex) { aViewModel.FriendlyMessage.Add(MessageStore.Get("SYS01")); Logger.Error("Agent Controller - Update " + ex.Message); } return(Index(wareViewModel)); }
public ActionResult AgentForm(int?id) { AgentViewModel agent = new AgentViewModel(); IEnumerable <SelectListItem> cities = _context.Countries.Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.Name, Selected = false }).ToList(); if (id == null) { ViewBag.VTitle = "Create"; } else { ViewBag.VTitle = "Edit"; agent = _context.Database.SqlQuery <AgentViewModel>("exec GetAgent @AgentCode", new SqlParameter("@AgentCode", id)).FirstOrDefault(); } agent.Countrylist = cities; return(View(agent)); }
// GET: Agents/Details/5 /// <summary> /// /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task <IActionResult> Details(int?id) { AgentViewModel vm; if (id == 0) { vm = new AgentViewModel(_context); } else { var agent = await _context.Agent .FirstOrDefaultAsync(m => m.Id == id); if (agent == null) { return(NotFound()); } vm = new AgentViewModel(_context, agent); } return(View(vm)); }
public ActionResult CreateAgent(AgentViewModel agents) { using (DataStoreContext db = new DataStoreContext()) { if (ModelState.IsValid) { Agent agent = new Agent { Name = agents.Name, Location = agents.Location, Address = agents.Address, PhoneNumber = agents.PhoneNumber, Active = agents.Active }; db.Agent.Add(agent); db.SaveChanges(); return(RedirectToAction("Agents")); } return(View(agents)); } }
public IActionResult Edit() { int id = int.Parse(User.FindFirst(x => x.Type == System.Security.Claims.ClaimTypes.NameIdentifier).Value); var model = _agentService.GetById(id); var agentModel = new AgentViewModel() { Id = model.Id, CompanyName = model.CompanyName, CreatedBy = model.CreatedBy, ConfirmPassword = model.ConfirmPassword, CreatedDate = model.CreatedDate, FirstName = model.FirstName, LastName = model.LastName, IsActive = model.IsActive, Password = model.Password, UpdatedBy = model.UpdatedBy, UpdatedDate = model.UpdatedDate, UserName = model.UserName }; return(View(agentModel)); }
public override JsonResult Get() { try { var Agents = _repository.GetAll(); var AgentsVm = Agents.Select(x => AgentViewModel.FromEntity(x)); if (AgentsVm == null) { return(Json(null)); } return(Json(AgentsVm)); //return new string[] { "value1", "value2" }; } catch (Exception ex) { _logger.LogError($"Failed to get Agents", ex); Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json("Failed to get Agents")); } }
public async Task <IActionResult> UpdateProfileOfAgent(string userId) { if (userId == null) { return(NotFound()); } var agent = await _context.Agents.FirstOrDefaultAsync(m => m.Id == userId); if (agent == null) { return(NotFound()); } var agentViewModel = new AgentViewModel { Id = agent.Id, Name = agent.Name, OldLogoFileName = agent.LogoFileName, PhoneNumber = agent.PhoneNumber }; return(View(agentViewModel)); }
public AgentViewModel GetAgentDetailById(string id) { AgentViewModel agentViewModel = null; Guid agentId; Guid.TryParse(id, out agentId); var agent = base.Find(null, a => a.Id == agentId && a.IsDeleted == false); if (agent != null) { var agentView = from a in agent.Items join c in dbContext.Credentials on a.CredentialId equals c.Id into table1 from c in table1.DefaultIfEmpty() select new AgentViewModel { Id = (a == null || a.Id == null) ? Guid.Empty : a.Id.Value, Name = a.Name, MachineName = a.MachineName, MacAddresses = a.MacAddresses, IPAddresses = a.IPAddresses, IsEnabled = a.IsEnabled, LastReportedOn = a.LastReportedOn, LastReportedStatus = a.LastReportedStatus, LastReportedWork = a.LastReportedWork, LastReportedMessage = a.LastReportedMessage, IsHealthy = a.IsHealthy, IsConnected = a.IsConnected, CredentialId = a.CredentialId, CredentialName = c?.Name }; agentViewModel = agentView.FirstOrDefault(); } return(agentViewModel); }
public HttpResponseMessage GetAgentByOpenIdOld([FromUri] GetByOpenIdRequest request) { _logInfo.Info(string.Format("获取代理人接口(老)请求串:{0}", Request.RequestUri)); var viewModel = new AgentViewModel(); if (!ModelState.IsValid) { viewModel.BusinessStatus = -10000; string msg = ModelState.Values.Where(item => item.Errors.Count == 1).Aggregate(string.Empty, (current, item) => current + (item.Errors[0].ErrorMessage + "; ")); viewModel.StatusMessage = "输入参数错误," + msg; return(viewModel.ResponseToJson()); } var response = _agentService.GetAgentByOpenIdOld(request, Request.GetQueryNameValuePairs()); if (response.Status == HttpStatusCode.BadRequest || response.Status == HttpStatusCode.Forbidden) { viewModel.BusinessStatus = -10001; viewModel.StatusMessage = "参数校验错误,请检查您的校验码"; return(viewModel.ResponseToJson()); } if (response.Status == HttpStatusCode.ExpectationFailed) { viewModel.BusinessStatus = -10003; viewModel.StatusMessage = "服务发生异常"; } if (response.ErrCode == -1) { viewModel.BusinessStatus = -1; viewModel.StatusMessage = "无代理人信息"; } else { viewModel.Agent = response.agent.ConverToViewModel(); viewModel.BusinessStatus = 1; } return(viewModel.ResponseToJson()); }
public HttpResponseMessage UpdateAgent(AgentViewModel agent) { try { var objAgentInfo = AgentManager.Instance.GetAgent(PortalSettings.PortalId, agent.AgentID); objAgentInfo.PortalID = PortalSettings.PortalId; objAgentInfo.Priority = agent.Priority; objAgentInfo.Enabled = agent.Enabled; AgentManager.Instance.UpdateAgent(objAgentInfo); DepartmentAgentManager.Instance.DeleteAgentDepartments(agent.AgentID); var departments = DepartmentManager.Instance.GetDepartments(PortalSettings.PortalId); foreach (var item in agent.Departments) { var department = departments.FirstOrDefault(d => d.DepartmentName == item); if (department == null) { continue; } var objDepartmentAgentInfo = new DepartmentAgentInfo() { DepartmentID = department.DepartmentID, AgentID = agent.AgentID, UserID = agent.UserID }; DepartmentAgentManager.Instance.AddDepartmentAgent(objDepartmentAgentInfo); } return(Request.CreateResponse(HttpStatusCode.OK, new { Success = true })); } catch (Exception ex) { Logger.Error(ex); return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public IActionResult Create(AgentViewModel model) { if (model == null) { return(NotFound()); } if (ModelState.IsValid) { var agent = _mapper.Map <AgentViewModel, Agent>(model); agent.AddedBy = _admin.Name; agent.AddedDate = DateTime.Now; if (model.File != null) { agent.Image = _fileManager.Upload(model.File); } else { agent.Image = null; } _homeRepository.AddAgent(agent); return(RedirectToAction("index")); } return(View(model)); }
private void RestructureViewModel(AgentViewModel changingViewModel, TreeViewModel viewModel) { viewModel.Community.RemoveItem(changingViewModel); viewModel.Community.AddItem(changingViewModel); changingViewModel.Select(); }
private AgentViewModel SaveAgent(AgentViewModel vm, string btnAddMap, string ddlDataMaps, string btnAddChrome, string ddlAgentChromes, string dataMapAgentNextOrder, string btnAddSchedule, string ddlDay, string ddlHour, string ddlMinute) { var isUpdate = false; var agent = new Agent(); if (vm.Id > 0) { isUpdate = true; agent = dataFlowDbContext.Agents.FirstOrDefault(x => x.Id == vm.Id); agent.Id = vm.Id; } agent.Name = vm.Name; agent.AgentTypeCode = vm.AgentTypeCode; agent.AgentAction = vm.AgentAction; agent.Url = vm.Url; agent.LoginUrl = vm.LoginUrl; agent.Username = vm.Username; if (vm.Password != null) { agent.Password = Encryption.Encrypt(vm.Password, EncryptionKey); } agent.Directory = vm.Directory ?? GetManualAgentBaseDirectory(agent); agent.FilePattern = vm.FilePattern; agent.Enabled = vm.Enabled; agent.Queue = Guid.NewGuid(); agent.Custom = vm.Custom; if (!isUpdate) { agent.Created = DateTime.Now; } if (btnAddChrome != null && int.TryParse(ddlAgentChromes, out var agentChromeId)) { agent.AgentAgentChromes = new List <AgentAgentChrome> { new AgentAgentChrome { AgentChromeId = agentChromeId } }; } if (btnAddMap != null && int.TryParse(ddlDataMaps, out var dataMapId)) { var lastProcessOrder = Convert.ToInt32(dataMapAgentNextOrder) + 1; agent.DataMapAgents = new List <DataMapAgent> { new DataMapAgent { DataMapId = dataMapId, ProcessingOrder = lastProcessOrder } }; } if (btnAddSchedule != null && int.TryParse(ddlDay, out var day) && int.TryParse(ddlHour, out var hour) && int.TryParse(ddlMinute, out var minute)) { agent.AgentSchedules = new List <AgentSchedule> { new AgentSchedule { Day = day, Hour = hour, Minute = minute } }; } dataFlowDbContext.Agents.AddOrUpdate(agent); dataFlowDbContext.SaveChanges(); var savevm = MapperService.Map <AgentViewModel>(agent); LogService.Info(LogTemplates.InfoCrud("Agent", agent.Name, agent.Id, isUpdate ? LogTemplates.EntityAction.Modified : LogTemplates.EntityAction.Added)); return(savevm); }
public async Task<ActionResult> Edit(AgentViewModel vm, HttpPostedFileBase imageFile) { try { if (ModelState.IsValid) { CloudBlockBlob imageBlob = null; if (imageFile != null && imageFile.ContentLength != 0) { // User is changing the image -- delete the existing // image blobs and then upload and save a new one. await _repository.DeleteBlobsAsync(vm.ImageUrl, vm.ThumbnailURL); imageBlob = await _repository.InsertImageBlob(imageFile); if (imageBlob != null) { vm.ImageUrl = imageBlob.Uri.ToString(); } } //map viewmodel to view var agent = AutoMapperConfig.TCWMapper.Map<Agent>(vm); //now save model to db _repository.Update(agent); await _repository.SaveAsync(); if (imageBlob != null) { _repository.AddMessageToQueue(agent.ID.ToString(), typeof(Agent).ToString()); } return RedirectToAction("Index"); } } catch (Exception ex) { //TODO: add logging } return View(vm); }
public AgentInfoUserControl(Agent a) { InitializeComponent(); DataContext = new AgentViewModel(a); }
public LogoutCommand(AgentViewModel agentViewModel) { AgentViewModel = agentViewModel; }
public void Throw_Excpetion_With_NullAgentProfile() { AgentViewModel target = new AgentViewModel(null); }
public HttpResponseMessage AddAgent(AgentViewModel agent) { try { if (agent.UserID == 0) { throw new Exception(); } Requires.NotNegative("agent.UserID", agent.UserID); var user = DotNetNuke.Entities.Users.UserController.GetUserById(PortalSettings.PortalId, agent.UserID); var objAgentInfo = new AgentInfo() { PortalID = PortalSettings.PortalId, UserID = agent.UserID, Priority = agent.Priority, Enabled = agent.Enabled, CreateByUser = UserInfo.UserID, CreateDate = DateTime.Now }; int agentID = AgentManager.Instance.AddAgent(objAgentInfo); agent.AgentID = agentID; if (!user.IsInRole("MyDnnSupportAgent")) { var role = RoleController.Instance.GetRoleByName(PortalSettings.PortalId, "MyDnnSupportAgent"); RoleController.AddUserRole(user, role, PortalSettings, DotNetNuke.Security.Roles.RoleStatus.Approved, Null.NullDate, Null.NullDate, true, false); } var departments = DepartmentManager.Instance.GetDepartments(PortalSettings.PortalId); foreach (var item in agent.Departments) { var department = departments.FirstOrDefault(d => d.DepartmentName == item); if (department == null) { continue; } var objDepartmentAgentInfo = new DepartmentAgentInfo() { DepartmentID = department.DepartmentID, AgentID = agentID, UserID = agent.UserID }; DepartmentAgentManager.Instance.AddDepartmentAgent(objDepartmentAgentInfo); } agent.Email = user.Email; return(Request.CreateResponse(HttpStatusCode.OK, new { Success = true, Agent = agent })); } catch (Exception ex) { Logger.Error(ex); string msg = ex.Message; if (((System.Data.SqlClient.SqlException)(ex)).Number == 2627) // user entekhab shode ghablan dar system be onvane agent sabt shode ast { msg = string.Format(Localization.Instance.GetString(DotNetNuke.Common.Globals.ResolveUrl("~/MyDnnPackage/dnn8contest/Website/DesktopModules/MVC/MyDnnSupport/LiveChat/App_LocalResources/SharedResources"), PortalSettings.CultureCode, "DuplicateAgent.Text"), agent.DisplayName); } return(Request.CreateResponse(HttpStatusCode.InternalServerError, msg)); } }
public async Task TestAgentManager() { //arrange var options = new DbContextOptionsBuilder <StorageContext>() .UseInMemoryDatabase(databaseName: "AgentManager") .Options; Guid credentialId = Guid.NewGuid(); Guid agentId = Guid.NewGuid(); var context = new StorageContext(options); var dummyAgent = new Agent { Id = agentId, Name = "TesterAgent", MachineName = "TestingMachine", MacAddresses = "00:00:00:a1:2b:cc", IPAddresses = "192.165.1.91", CredentialId = credentialId }; var dummyAgentHeartbeat = new AgentHeartbeat { Id = Guid.NewGuid(), AgentId = agentId }; var dummyCredential = new Credential { Id = credentialId, Name = "TesterCredential" }; var dummyUserAgent = new AspNetUsers { Id = Guid.NewGuid().ToString(), UserName = "******", Name = "TesterAgent" }; var dummyJob = new Job { Id = Guid.NewGuid(), AgentId = agentId, JobStatus = JobStatusType.New }; Seed(context, dummyAgent, dummyCredential, dummyUserAgent, dummyJob, dummyAgentHeartbeat); var agentLogger = Mock.Of <ILogger <Agent> >(); var usersLogger = Mock.Of <ILogger <AspNetUsers> >(); var scheduleLogger = Mock.Of <ILogger <Schedule> >(); var jobLogger = Mock.Of <ILogger <Job> >(); var credentialLogger = Mock.Of <ILogger <Credential> >(); var agentHeartbeatLogger = Mock.Of <ILogger <AgentHeartbeat> >(); var httpContextAccessor = new Mock <IHttpContextAccessor>(); httpContextAccessor.Setup(req => req.HttpContext.User.Identity.Name).Returns(It.IsAny <string>()); var userRepo = new AspNetUsersRepository(context, usersLogger, httpContextAccessor.Object); var agentRepo = new AgentRepository(context, agentLogger, httpContextAccessor.Object); var scheduleRepo = new ScheduleRepository(context, scheduleLogger, httpContextAccessor.Object); var jobRepo = new JobRepository(context, jobLogger, httpContextAccessor.Object); var credentialRepo = new CredentialRepository(context, credentialLogger, httpContextAccessor.Object); var agentHeartbeatRepo = new AgentHeartbeatRepository(context, agentHeartbeatLogger, httpContextAccessor.Object); /*var manager = new AgentManager(agentRepo, scheduleRepo, jobRepo,userRepo, credentialRepo, agentHeartbeatRepo);*/ //act AgentViewModel view = new AgentViewModel(); Agent agentModel = agentRepo.GetOne(agentId); view = view.Map(agentModel); /*var validAgentView = manager.GetAgentDetails(view);//Fetches agent details * bool agentWithDependant = manager.CheckReferentialIntegrity(agentId.ToString()); * * dummyJob.JobStatus = JobStatusType.Completed;//Removes referential integrity violation * bool agentWithoutDependant = manager.CheckReferentialIntegrity(agentId.ToString());*/ //assert /*Assert.Equal(dummyCredential.Name, validAgentView.CredentialName); * Assert.Equal(dummyUserAgent.UserName, validAgentView.UserName); * Assert.True(agentWithDependant); * Assert.False(agentWithoutDependant);*/ }
private void ExecuteJob() { // Log Event _fileLogger.LogEvent("Job Execution", "Job execution started"); // Peek Job var job = JobsQueueManager.PeekJob(); // Log Event _fileLogger.LogEvent("Job Execution", "Attempt to fetch Automation Detail"); // Get Automation Info var automation = AutomationsAPIManager.GetAutomation(_authAPIManager, job.AutomationId.ToString()); // Update LastReportedMessage and LastReportedWork _agentHeartbeat.LastReportedMessage = "Job execution started"; _agentHeartbeat.LastReportedWork = automation.Name; // Log Event _fileLogger.LogEvent("Job Execution", "Attempt to download/retrieve Automation"); string connectedUserName = _connectionSettingsManager.ConnectionSettings.UserName; string userDomainName = _connectionSettingsManager.ConnectionSettings.DNSHost; // Download Automation and Extract Files and Return File Paths of ProjectConfig and MainScript automation.AutomationEngine = string.IsNullOrEmpty(automation.AutomationEngine) ? "OpenBots" : automation.AutomationEngine; string configFilePath; string executionDirPath; var mainScriptFilePath = AutomationManager.DownloadAndExtractAutomation(_authAPIManager, automation, job.Id.ToString(), userDomainName, connectedUserName, out executionDirPath, out configFilePath); // Install Project Dependencies List <string> assembliesList = null; if (automation.AutomationEngine == "OpenBots") { NugetPackageManager.InstallProjectDependencies(configFilePath, userDomainName, connectedUserName); assembliesList = NugetPackageManager.LoadPackageAssemblies(configFilePath, userDomainName, connectedUserName); } // Log Event _fileLogger.LogEvent("Job Execution", "Attempt to update Job Status (Pre-execution)"); // Create Automation Execution Log (Execution Started) _executionLog = ExecutionLogsAPIManager.CreateExecutionLog(_authAPIManager, new AutomationExecutionLog( null, false, null, DateTime.UtcNow, null, null, null, null, null, job.Id, job.AutomationId, job.AgentId, DateTime.UtcNow, null, null, null, "Job has started processing")); // Update Job Status (InProgress) JobsAPIManager.UpdateJobStatus(_authAPIManager, job.AgentId.ToString(), job.Id.ToString(), JobStatusType.InProgress, new JobErrorViewModel()); // Update Job Start Time JobsAPIManager.UpdateJobPatch(_authAPIManager, job.Id.ToString(), new List <Operation>() { new Operation() { Op = "replace", Path = "/startTime", Value = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'") } }); // Log Event _fileLogger.LogEvent("Job Execution", "Attempt to execute process"); AgentViewModel agent = AgentsAPIManager.GetAgent(_authAPIManager, job.AgentId.ToString()); var userCredential = CredentialsAPIManager.GetCredentials(_authAPIManager, agent.CredentialId.ToString()); MachineCredential credential = new MachineCredential { Name = userCredential.Name, Domain = userCredential.Domain, UserName = userCredential.UserName, PasswordSecret = userCredential.PasswordSecret }; // Run Automation RunAutomation(job, automation, credential, mainScriptFilePath, executionDirPath, assembliesList); // Log Event _fileLogger.LogEvent("Job Execution", "Job execution completed"); // Log Event _fileLogger.LogEvent("Job Execution", "Attempt to update Job Status (Post-execution)"); // Update Job End Time JobsAPIManager.UpdateJobPatch(_authAPIManager, job.Id.ToString(), new List <Operation>() { new Operation() { Op = "replace", Path = "/endTime", Value = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'") }, new Operation() { Op = "replace", Path = "/isSuccessful", Value = true } }); // Delete Job Directory try { Directory.Delete(executionDirPath, true); } catch (Exception) { // Appended 'Long Path Specifier' before the Directory Path Directory.Delete(@"\\?\" + executionDirPath, true); } // Update Automation Execution Log (Execution Finished) _executionLog.CompletedOn = DateTime.UtcNow; _executionLog.Status = "Job has finished processing"; ExecutionLogsAPIManager.UpdateExecutionLog(_authAPIManager, _executionLog); // Update Job Status (Completed) JobsAPIManager.UpdateJobStatus(_authAPIManager, job.AgentId.ToString(), job.Id.ToString(), JobStatusType.Completed, new JobErrorViewModel()); _fileLogger.LogEvent("Job Execution", "Job status updated. Removing from queue."); // Dequeue the Job JobsQueueManager.DequeueJob(); _isSuccessfulExecution = true; _agentHeartbeat.LastReportedMessage = "Job execution completed"; }
public IActionResult Details(string announceType, int categoryId, int cityId, int metroId, int minPrice, int maxPrice, int minArea, int maxArea, int minRoom, int minBath, int agentId) { var model = new AgentViewModel(); model.Homes = db.Homes .Include(h => h.Category) .Include(h => h.Metro) .Include(h => h.City) .Include(h => h.Images) .Where(h => h.AgentId == agentId) .Where(h => h.AnnounceType == announceType) .ToList(); #region search if (categoryId != 0) { model.Homes = model.Homes.Where(h => h.CategoryId == categoryId).ToList(); } if (metroId != 0) { model.Homes = model.Homes.Where(h => h.MetroId == metroId).ToList(); } if (cityId != 0) { model.Homes = model.Homes.Where(h => h.CityId == cityId).ToList(); } if (cityId != 0) { model.Homes = model.Homes.Where(h => h.CityId == cityId).ToList(); } if (minPrice != 0) { model.Homes = model.Homes.Where(h => h.Price >= minPrice).ToList(); } if (maxPrice != 0) { model.Homes = model.Homes.Where(h => h.Price <= maxPrice).ToList(); } if (minRoom != 0) { model.Homes = model.Homes.Where(h => h.RoomCount >= minRoom).ToList(); } if (minBath != 0) { model.Homes = model.Homes.Where(h => h.BathCount >= minBath).ToList(); } #endregion model.Agent = db.Agents.Where(a => a.Id == agentId).FirstOrDefault(); ViewData["CategoryId"] = new SelectList(db.Categories, "Id", "Name", categoryId); var cities = db.Cities.OrderBy(a => a.Id); ViewData["CityId"] = new SelectList(cities, "Id", "Name", cityId); ViewData["MetroId"] = new SelectList(db.Metros, "Id", "Name", metroId); #region Selected items if (announceType == null || announceType == "") { ViewBag.AnnounceTypeSelected = "Sale"; } else { ViewBag.AnnounceTypeSelected = announceType; } if (minPrice == 0) { ViewBag.MinPriceSelected = ""; } else { ViewBag.MinPriceSelected = minPrice; } if (maxPrice == 0) { ViewBag.MaxPriceSelected = ""; } else { ViewBag.MaxPriceSelected = maxPrice; } if (minArea == 0) { ViewBag.MinAreaSelected = ""; } else { ViewBag.MinAreaSelected = minArea; } if (maxArea == 0) { ViewBag.MaxAreaSelected = ""; } else { ViewBag.MaxAreaSelected = maxArea; } if (minRoom == 0) { ViewBag.MinRoomSelected = @"<option hidden value='0'>All</option>"; } else if (minRoom == 5) { ViewBag.MinRoomSelected = @"<option hidden value='5'>5 və daha çox</option>"; } else { ViewBag.MinRoomSelected = @$ "<option hidden>{minRoom}</option>"; } if (minBath == 0) { ViewBag.MinBathSelected = @"<option hidden value='0'>All</option>"; } else if (minBath == 4) { ViewBag.MinBathSelected = @"<option hidden value='4'>4 və daha çox</option>"; } else { ViewBag.MinBathSelected = @$ "<option hidden>{minBath}</option>"; } #endregion return(View(model)); }
public ActionResult Create(AgentViewModel AgentVm) { if (AgentVm.LedgerAccountGroupId == 0) { PrepareViewBag(); return(View(AgentVm).Danger("Account Group field is required")); } if (_PersonService.CheckDuplicate(AgentVm.Name, AgentVm.Suffix, AgentVm.PersonId) == true) { PrepareViewBag(); return(View(AgentVm).Danger("Combination of name and sufix is duplicate")); } if (ModelState.IsValid) { if (AgentVm.PersonId == 0) { Person person = Mapper.Map <AgentViewModel, Person>(AgentVm); BusinessEntity businessentity = Mapper.Map <AgentViewModel, BusinessEntity>(AgentVm); Agent Agent = Mapper.Map <AgentViewModel, Agent>(AgentVm); PersonAddress personaddress = Mapper.Map <AgentViewModel, PersonAddress>(AgentVm); LedgerAccount account = Mapper.Map <AgentViewModel, LedgerAccount>(AgentVm); person.CreatedDate = DateTime.Now; person.ModifiedDate = DateTime.Now; person.CreatedBy = User.Identity.Name; person.ModifiedBy = User.Identity.Name; person.ObjectState = Model.ObjectState.Added; new PersonService(_unitOfWork).Create(person); _BusinessEntityService.Create(businessentity); _AgentService.Create(Agent); personaddress.AddressType = AddressTypeConstants.Work; personaddress.CreatedDate = DateTime.Now; personaddress.ModifiedDate = DateTime.Now; personaddress.CreatedBy = User.Identity.Name; personaddress.ModifiedBy = User.Identity.Name; personaddress.ObjectState = Model.ObjectState.Added; _PersonAddressService.Create(personaddress); account.LedgerAccountName = person.Name; account.LedgerAccountSuffix = person.Suffix; account.CreatedDate = DateTime.Now; account.ModifiedDate = DateTime.Now; account.CreatedBy = User.Identity.Name; account.ModifiedBy = User.Identity.Name; account.ObjectState = Model.ObjectState.Added; _AccountService.Create(account); try { _unitOfWork.Save(); } catch (Exception ex) { string message = _exception.HandleException(ex); ModelState.AddModelError("", message); return(View(AgentVm)); } #region //Saving Images if any uploaded after UnitOfWorkSave if (Request.Files[0] != null && Request.Files[0].ContentLength > 0) { //For checking the first time if the folder exists or not----------------------------- string uploadfolder; int MaxLimit; int.TryParse(ConfigurationManager.AppSettings["MaxFileUploadLimit"], out MaxLimit); var x = (from iid in db.Counter select iid).FirstOrDefault(); if (x == null) { uploadfolder = System.Guid.NewGuid().ToString(); Counter img = new Counter(); img.ImageFolderName = uploadfolder; img.ModifiedBy = User.Identity.Name; img.CreatedBy = User.Identity.Name; img.ModifiedDate = DateTime.Now; img.CreatedDate = DateTime.Now; new CounterService(_unitOfWork).Create(img); _unitOfWork.Save(); } else { uploadfolder = x.ImageFolderName; } //For checking if the image contents length is greater than 100 then create a new folder------------------------------------ if (!Directory.Exists(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder))) { Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)); } int count = Directory.GetFiles(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)).Length; if (count >= MaxLimit) { uploadfolder = System.Guid.NewGuid().ToString(); var u = new CounterService(_unitOfWork).Find(x.CounterId); u.ImageFolderName = uploadfolder; new CounterService(_unitOfWork).Update(u); _unitOfWork.Save(); } //Saving Thumbnails images: Dictionary <string, string> versions = new Dictionary <string, string>(); //Define the versions to generate versions.Add("_thumb", "maxwidth=100&maxheight=100"); //Crop to square thumbnail versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg string temp2 = ""; string filename = System.Guid.NewGuid().ToString(); foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys) { HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey]; if (pfile.ContentLength <= 0) { continue; //Skip unused file controls. } temp2 = Path.GetExtension(pfile.FileName); string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder); if (!Directory.Exists(uploadFolder)) { Directory.CreateDirectory(uploadFolder); } string filecontent = Path.Combine(uploadFolder, AgentVm.Name + "_" + filename); //pfile.SaveAs(filecontent); ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true)); //Generate each version foreach (string suffix in versions.Keys) { if (suffix == "_thumb") { string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs"); if (!Directory.Exists(tuploadFolder)) { Directory.CreateDirectory(tuploadFolder); } //Generate a filename (GUIDs are best). string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename); //Let the image builder add the correct extension based on the output file type //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true); ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true)); } else if (suffix == "_medium") { string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium"); if (!Directory.Exists(tuploadFolder)) { Directory.CreateDirectory(tuploadFolder); } //Generate a filename (GUIDs are best). string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename); //Let the image builder add the correct extension based on the output file type //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true); ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true)); } } //var tempsave = _FinishedProductService.Find(pt.ProductId); person.ImageFileName = AgentVm.Name + "_" + filename + temp2; person.ImageFolderName = uploadfolder; person.ObjectState = Model.ObjectState.Modified; _PersonService.Update(person); _unitOfWork.Save(); } } #endregion //return RedirectToAction("Create").Success("Data saved successfully"); return(RedirectToAction("Edit", new { id = person.PersonID }).Success("Data saved Successfully")); } else { //string tempredirect = (Request["Redirect"].ToString()); Person person = Mapper.Map <AgentViewModel, Person>(AgentVm); BusinessEntity businessentity = Mapper.Map <AgentViewModel, BusinessEntity>(AgentVm); Agent Agent = Mapper.Map <AgentViewModel, Agent>(AgentVm); PersonAddress personaddress = _PersonAddressService.Find(AgentVm.PersonAddressID); LedgerAccount account = _AccountService.Find(AgentVm.AccountId); StringBuilder logstring = new StringBuilder(); person.ModifiedDate = DateTime.Now; person.ModifiedBy = User.Identity.Name; new PersonService(_unitOfWork).Update(person); _BusinessEntityService.Update(businessentity); _AgentService.Update(Agent); personaddress.Address = AgentVm.Address; personaddress.CityId = AgentVm.CityId; personaddress.Zipcode = AgentVm.Zipcode; personaddress.ModifiedDate = DateTime.Now; personaddress.ModifiedBy = User.Identity.Name; personaddress.ObjectState = Model.ObjectState.Modified; _PersonAddressService.Update(personaddress); account.LedgerAccountName = person.Name; account.LedgerAccountSuffix = person.Suffix; account.ModifiedDate = DateTime.Now; account.ModifiedBy = User.Identity.Name; _AccountService.Update(account); ////Saving Activity Log:: ActivityLog al = new ActivityLog() { ActivityType = (int)ActivityTypeContants.Modified, DocId = AgentVm.PersonId, Narration = logstring.ToString(), CreatedDate = DateTime.Now, CreatedBy = User.Identity.Name, //DocTypeId = new DocumentTypeService(_unitOfWork).FindByName(TransactionDocCategoryConstants.ProcessSequence).DocumentTypeId, }; new ActivityLogService(_unitOfWork).Create(al); //End of Saving ActivityLog try { _unitOfWork.Save(); } catch (Exception ex) { string message = _exception.HandleException(ex); ModelState.AddModelError("", message); return(View("Create", AgentVm)); } #region //Saving Image if file is uploaded if (Request.Files[0] != null && Request.Files[0].ContentLength > 0) { string uploadfolder = AgentVm.ImageFolderName; string tempfilename = AgentVm.ImageFileName; if (uploadfolder == null) { var x = (from iid in db.Counter select iid).FirstOrDefault(); if (x == null) { uploadfolder = System.Guid.NewGuid().ToString(); Counter img = new Counter(); img.ImageFolderName = uploadfolder; img.ModifiedBy = User.Identity.Name; img.CreatedBy = User.Identity.Name; img.ModifiedDate = DateTime.Now; img.CreatedDate = DateTime.Now; new CounterService(_unitOfWork).Create(img); _unitOfWork.Save(); } else { uploadfolder = x.ImageFolderName; } } //Deleting Existing Images //ConfigurationManager.AppSettings["PhysicalRDLCPath"] + uploadfolder + "/" + tempfilename; var xtemp = System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename); if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename))) { System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename)); } //Deleting Thumbnail Image: if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename))) { System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename)); } //Deleting Medium Image: if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename))) { System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename)); } //Saving Thumbnails images: Dictionary <string, string> versions = new Dictionary <string, string>(); //Define the versions to generate versions.Add("_thumb", "maxwidth=100&maxheight=100"); //Crop to square thumbnail versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg string temp2 = ""; string filename = System.Guid.NewGuid().ToString(); foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys) { HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey]; if (pfile.ContentLength <= 0) { continue; //Skip unused file controls. } temp2 = Path.GetExtension(pfile.FileName); string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder); if (!Directory.Exists(uploadFolder)) { Directory.CreateDirectory(uploadFolder); } string filecontent = Path.Combine(uploadFolder, AgentVm.Name + "_" + filename); //pfile.SaveAs(filecontent); ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true)); //Generate each version foreach (string suffix in versions.Keys) { if (suffix == "_thumb") { string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs"); if (!Directory.Exists(tuploadFolder)) { Directory.CreateDirectory(tuploadFolder); } //Generate a filename (GUIDs are best). string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename); //Let the image builder add the correct extension based on the output file type //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true); ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true)); } else if (suffix == "_medium") { string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium"); if (!Directory.Exists(tuploadFolder)) { Directory.CreateDirectory(tuploadFolder); } //Generate a filename (GUIDs are best). string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename); //Let the image builder add the correct extension based on the output file type //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true); ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true)); } } } person.ImageFileName = person.Name + "_" + filename + temp2; person.ImageFolderName = uploadfolder; _PersonService.Update(person); _unitOfWork.Save(); } #endregion return(RedirectToAction("Index").Success("Data saved successfully")); } } PrepareViewBag(); return(View(AgentVm)); }
public void Throw_Exception_With_EmpyAgent_In_AgentProfile() { AgentProfile profile = new AgentProfile(string.Empty); AgentViewModel target = new AgentViewModel(profile); }
public UserPageCommand(AgentViewModel agentViewModel) { AgentViewModel = agentViewModel; }
// ********************** // AGENT INFORMATION -- view, create, edit // ********************** public ActionResult Agents() { DataStoreContext db = new DataStoreContext(); var agents = (from a in db.Agent join i in db.Invoice on a.AgentId equals i.AgentId orderby a.Name select new AgentViewModel { AgentId = a.AgentId, Name = a.Name, Location = a.Location, Active = a.Active, PieceSold = i.PieceSold }).ToList(); foreach (var agent in agents) { string[] pieces = agent.PieceSold.Split(','); double totalSales = 0; double totalProfit = 0; foreach (var piece in pieces) { var individualSale = ( from ip in db.IndividualPiece where ip.Sold == true join aw in db.ArtWork on ip.ArtWorkId equals aw.ArtWorkId where aw.Title == piece select new PriceViewModel { Price = ip.Price, Cost = ip.Cost }).ToList(); if (individualSale.Count > 0) { totalSales += individualSale[0].Price; double profit = individualSale[0].Price - individualSale[0].Cost; totalProfit += profit; } } agent.Sales = Math.Round(totalSales, 2); agent.Profit = Math.Round(totalProfit, 2); } // brute force solution for displaying unique agents & profit/sales totals for (int i = 0; i < agents.Count; i++) { if ((i + 1 != agents.Count) && agents[i].Name == agents[i + 1].Name) { if (agents[i + 2].Name == agents[i + 1].Name) { agents[i + 1].PieceSold += "," + agents[i + 2].PieceSold; agents[i + 1].Sales += agents[i + 2].Sales; agents[i + 1].Profit += agents[i + 2].Profit; agents.Remove(agents[i + 2]); } agents[i + 1].PieceSold += ", " + agents[i].PieceSold; agents[i + 1].Sales += agents[i].Sales; agents[i + 1].Profit += agents[i].Profit; agents.Remove(agents[i]); } } // need to add new agents to this list // new agent = not represented on above agents list, // will not have an invoice var potentialNewAgents = db.Agent.ToList(); foreach (var potentialNewAgent in potentialNewAgents) { if (potentialNewAgent.AgentId > 7) { AgentViewModel newAgent = new AgentViewModel { Name = potentialNewAgent.Name, Location = potentialNewAgent.Location, PieceSold = "none", Active = potentialNewAgent.Active }; agents.Add(newAgent); } } AgentSalesViewModel agentSales = new AgentSalesViewModel { Agents = agents }; return(View(agentSales)); }
//[AuthorizeUser(RoleModule.Agent, Function.View)] public ActionResult Index(AgentViewModel aViewModel) { aViewModel.BranchInfoList = _branchManager.GetBranchList(); return(View("Index", aViewModel)); }
public StackLayout AssignValues() { BindingContext = new AgentViewModel(Navigation, this.ilm); var label = new Label { Text = "Registration", BackgroundColor = Color.Black, Font = Font.SystemFontOfSize(NamedSize.Large), TextColor = Color.White, VerticalOptions = LayoutOptions.Center, XAlign = TextAlignment.Center, // Center the text in the blue box. YAlign = TextAlignment.Center // Center the text in the blue box. }; var emailLabel = new Label { HorizontalOptions = LayoutOptions.Fill }; emailLabel.Text = "Email"; var emailText = new Entry() { HorizontalOptions = LayoutOptions.FillAndExpand }; emailText.SetBinding(Entry.TextProperty, AgentViewModel.AgentEmailPropertyName); emailText.Keyboard = Keyboard.Email; var firstNameLabel = new Label { HorizontalOptions = LayoutOptions.Fill }; firstNameLabel.Text = "First Name"; var firstName = new MyEntry() { HorizontalOptions = LayoutOptions.FillAndExpand }; firstName.SetBinding(MyEntry.TextProperty, AgentViewModel.FirstNamePropertyName); var lastNameLabel = new Label { HorizontalOptions = LayoutOptions.Fill }; lastNameLabel.Text = "Last Name"; var lastName = new MyEntry() { HorizontalOptions = LayoutOptions.FillAndExpand }; lastName.SetBinding(MyEntry.TextProperty, AgentViewModel.LastNamePropertyName); var agencyLabel = new Label { HorizontalOptions = LayoutOptions.Fill }; agencyLabel.Text = "Agency"; var agencyText = new MyEntry() { HorizontalOptions = LayoutOptions.FillAndExpand }; agencyText.SetBinding(MyEntry.TextProperty, AgentViewModel.AgencyNamePropertyName); var phoneLabel = new Label { HorizontalOptions = LayoutOptions.Fill }; phoneLabel.Text = "Phone number"; var phoneText = new Entry() { HorizontalOptions = LayoutOptions.FillAndExpand }; phoneText.SetBinding(Entry.TextProperty, AgentViewModel.PhonePropertyName); phoneText.Keyboard = Keyboard.Telephone; var chkInvite = new CheckBox(); chkInvite.SetBinding(CheckBox.CheckedProperty, AgentViewModel.isCheckedPropertyName, BindingMode.TwoWay); chkInvite.DefaultText = "I Agree to the terms and condition"; chkInvite.IsVisible = true; Button btnRegister = new Button { HorizontalOptions = LayoutOptions.Fill, BackgroundColor = Color.FromHex("22498a"), Text = "Register" }; btnRegister.SetBinding(Button.CommandProperty, AgentViewModel.SubmitCommandPropertyName); var loginButton = new Button { Text = "I already have a recruiter account...", BackgroundColor = Color.FromHex("3b73b9"), TextColor = Color.White }; loginButton.SetBinding(Button.CommandProperty, AgentViewModel.GotoLoginCommandPropertyName); var downloadButton = new Button { Text = "Download Terms and Conditions", BackgroundColor = Color.FromHex("f7941d"), TextColor = Color.White }; downloadButton.Clicked += (object sender, EventArgs e) => { DependencyService.Get <FormSample.Helpers.Utility.IUrlService>().OpenUrl(Utility.PDFURL); }; var lableStakelayout = new StackLayout() { Children = { label }, Orientation = StackOrientation.Vertical }; var controlLayout = new StackLayout() { Padding = new Thickness(Device.OnPlatform(5, 5, 5), 0, Device.OnPlatform(5, 5, 5), 0), //new Thickness(5,0,5,0), VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.Fill, Orientation = StackOrientation.Vertical, Children = { emailLabel, emailText, firstNameLabel, firstName, lastNameLabel, lastName, agencyLabel, agencyText, phoneLabel, phoneText, chkInvite } }; var scrollableContentLayout = new ScrollView() { Content = controlLayout, Orientation = ScrollOrientation.Vertical, HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.FillAndExpand }; var buttonLayout = new StackLayout() { Padding = new Thickness(Device.OnPlatform(5, 5, 5), 0, Device.OnPlatform(5, 5, 5), 0), //new Thickness(5,0,5,0), HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.FillAndExpand, Orientation = StackOrientation.Vertical, Children = { btnRegister, loginButton, downloadButton } }; var nameLayout = new StackLayout() { HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.FillAndExpand, Orientation = StackOrientation.Vertical, Children = { lableStakelayout, scrollableContentLayout, buttonLayout } }; return(new StackLayout { Children = { nameLayout } }); }
public AccommodationPageCommand(AgentViewModel agentViewModel) { AgentViewModel = agentViewModel; }
public UserPageView(AgentViewModel agentViewModel) { InitializeComponent(); DataContext = new UserViewModel(agentViewModel); }