/// <summary> /// Book the table reservation /// </summary> /// <param name="bookingDetail">Booking detais</param> /// <returns></returns> public ServiceResponse<bool> BookTableReservation(BookingDetail bookingDetail) { // Add business rules var serviceResponse = new ServiceResponse<bool>(); try { var result = reservationRepository.BookTableReservation(bookingDetail); serviceResponse.Result = result; if (result == true) { serviceResponse.OperationSuccess = true; serviceResponse.ServiceMessage = "Booking successful"; } else { serviceResponse.OperationSuccess = false; serviceResponse.ServiceMessage = "Unable to book the reservation"; } } catch (Exception ex) { serviceResponse.ErrorMessage = ex.Message; } return serviceResponse; }
ServiceResponse<IList<BudgetReceipt>> ISearchEngine.FindBudgetItemDescriptions(ServiceRequest<BudgetReceipt> searchRequest) { var output = new ServiceResponse<IList<BudgetReceipt>>(); using (var unitOfWork = RepositoryManager<BudgetReceipt>.Instance.CreateWorkUnit()) { try { var repo = new Repository<BudgetReceipt>(unitOfWork.Session); var result = repo.FilterBy(x => (x.Subscriber.Id == _subscriber.Id && x.Description.StartsWith(searchRequest.Data.Description))).ToList(); unitOfWork.Commit(); output.Data = result.Distinct(new BudgetReceipt.DescriptionCompare()).ToList(); output.Result = Result.Successful; } catch (GenericADOException e) { output.Message = MessageFactory.CreateGenerator(RepositoryType.Postgres).GenerateErrorMessage(e); _logger.Critical(output.Message, e); output.Result = Result.Failure; } catch (Exception e) { _logger.Critical(e.Message, e); } } return output; }
public HttpResponseMessage CreateVolunteerTask(VolunteerTaskInfo task) { try { var timeStamp = DateTime.Now; task.CreatedByDate = timeStamp; task.CreatedByUserId = UserInfo.UserID; task.LastUpdatedByDate = timeStamp; task.LastUpdatedByUserId = UserInfo.UserID; VolunteerTaskDataAccess.CreateItem(task); var savedTask = VolunteerTaskDataAccess.GetItems(task.VolunteerId) .OrderByDescending(t => t.CreatedByDate) .FirstOrDefault(); var response = new ServiceResponse<VolunteerTaskInfo> { Content = savedTask }; return Request.CreateResponse(HttpStatusCode.OK, response.ObjectToJson()); } catch (Exception ex) { Exceptions.LogException(ex); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ERROR_MESSAGE); } }
public JsonResult AddEditAccount(AccountViewModel accountViewModel) { var accountModel = new AccountModel(); Mapper.Map(accountViewModel, accountModel); Mapper.Map(accountViewModel.CountryType, accountModel.CountryModel); Mapper.Map(accountViewModel.AccountAccountTypes, accountModel.AccountAccountTypeModel); Mapper.Map(accountViewModel.AccountCategories, accountModel.AccountCategoryModel); Mapper.Map(accountViewModel.AccountCompanies, accountModel.AccountCompanyModel); //for (int i = 0; i < accountViewModel.AccountTypes.Count; i++) //{ // accountModel.AccountAccountTypeModel //} var result = new ServiceResponse(); if (accountModel.AccountId > 0) { accountModel.AccountCategoryModel.ForEach(m => m.AccountId = accountModel.AccountId); accountModel.AccountAccountTypeModel.ForEach(m => m.AccountId = accountModel.AccountId); result = _accountService.UpdateAccountDetail(accountModel); } else { result = _accountService.SaveAccountDetail(accountModel); } AccountModel result1 = (AccountModel)result.Data; Mapper.Map(result1, accountViewModel); result.Data = accountViewModel; return Json(result, JsonRequestBehavior.AllowGet); }
public Task<ServiceResponse<IEnumerable<ResultFormatInformation>>> GetResultFormatsAsync() { var format = new ResultFormatInformation { DisplayName = "Excel", FileExtension = ".xlsx" }; var response = new ServiceResponse<IEnumerable<ResultFormatInformation>>(new[] { format }); return Task.FromResult(response); }
public HttpResponseMessage AssignRoomToTrack(int roomId, int trackId, int codeCampId) { try { var track = TrackDataAccess.GetItem(trackId, codeCampId); if (track != null) { track.RoomId = roomId; track.LastUpdatedByDate = DateTime.Now; track.LastUpdatedByUserId = UserInfo.UserID; TrackDataAccess.UpdateItem(track); } var response = new ServiceResponse<string> { Content = SUCCESS_MESSAGE }; if (track == null) { ServiceResponseHelper<string>.AddNoneFoundError("track", ref response); } return Request.CreateResponse(HttpStatusCode.OK, response.ObjectToJson()); } catch (Exception ex) { Exceptions.LogException(ex); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ERROR_MESSAGE); } }
public async Task<ServiceResponse<string>> GetResponseAsync(GoogleMapsParameters parameters) { var result = new ServiceResponse<string>() { Success = false, Message = "Failed to get a response from service" }; var uri = GetUri(parameters); using (var client = new HttpClient()) { try { result.Value = await client.GetStringAsync(uri); result.Success = true; result.Message = "Ok"; } catch (Exception) { throw; } } return result; }
public async Task<ServiceResponse<int>> GetAddressInfoAsync(DistanceMatrixParameters parameters, InfoType info) { var result = new ServiceResponse<int>() { Success = false, Message = "Failed to get Buration data from service" }; var response = await GetResponseAsync(parameters); if (response.Success) { var json = JsonConvert.DeserializeObject<DistanceMatrixResponse>(response.Value); var elem = json.Rows[0].Elements[0]; var propName = Enum.GetName(typeof(InfoType), (int)info); var item = elem.GetType().GetProperty(propName).GetValue(elem); var value = item.GetType().GetProperty("Value").GetValue(item); result.Value = (int)value; result.Success = true; result.Message = ""; } else { throw new Exception(response.Message, new Exception(response.Value)); } return result; }
public async Task<string> SaveActivity(string activity) { WCFProxy.AuthorisationManagerServiceClient authorisationManagerServiceClient = null; try { authorisationManagerServiceClient = new WCFProxy.AuthorisationManagerServiceClient(new WSHttpBinding(), new EndpointAddress(endpointAddress)); var result = await authorisationManagerServiceClient.SaveActivityAsync(activity).ConfigureAwait(false); authorisationManagerServiceClient.Close(); return result; } catch (Exception ex) { if (authorisationManagerServiceClient != null) { authorisationManagerServiceClient.Abort(); } var serviceResponse = new ServiceResponse(ex.Message, true); var response = Serializer.SerializeToJson(serviceResponse); return response; } }
public HttpResponseMessage AssignSessionToTimeSlot(int sessionId, int timeSlotId, int codeCampId) { try { var session = SessionDataAccess.GetItem(sessionId, codeCampId); if (session != null) { session.TimeSlotId = timeSlotId; session.LastUpdatedByDate = DateTime.Now; session.LastUpdatedByUserId = UserInfo.UserID; SessionDataAccess.UpdateItem(session); } var response = new ServiceResponse<string> { Content = SUCCESS_MESSAGE }; if (session == null) { ServiceResponseHelper<string>.AddNoneFoundError("session", ref response); } return Request.CreateResponse(HttpStatusCode.OK, response.ObjectToJson()); } catch (Exception ex) { Exceptions.LogException(ex); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ERROR_MESSAGE); } }
public JsonResult AddContact(string firstName, string middleName, string lastName, string email, string phone, int contactGroupId) { var result = new ServiceResponse<Object>(); var contact = new Contact { FirstName = firstName, MiddleName = middleName, LastName = lastName, Email = email, Phone = phone, ContactGroupId = contactGroupId }; try { _contactService.AddContact(contact); } catch (Exception ex) { Trace.WriteLine("AddContact: " + ex.Message); result.Message = ex.Message; } result.Result = GetAllGroupsResponse(); return JsonResponse(result); }
public ServiceResponse CreateMember(Member member, string originalPassword) { var result = new ServiceResponse(); member.PasswordSalt = CreateSalt(); member.HashedPassword = _formsAuth.HashPasswordForStoringInConfigFile(originalPassword + member.PasswordSalt, "sha1"); _memberRepo.Save(member); return result; }
public ServiceResponse<CodeCampInfo> GetEvent(int itemId) { var result = new ServiceResponse<CodeCampInfo>(); result = ServiceHelper.GetRequest<ServiceResponse<CodeCampInfo>>(fullApiUri + "GetEvent?itemId=" + itemId); return result; }
public ServiceResponse<string> DeleteEvent(int itemId) { var result = new ServiceResponse<string>(); result = ServiceHelper.DeleteRequest<ServiceResponse<string>>(fullApiUri + "DeleteEvent?itemId=" + itemId, string.Empty); return result; }
public ServiceResponse<string> CreateEvent(CodeCampInfo codeCamp) { var result = new ServiceResponse<string>(); result = ServiceHelper.PostRequest<ServiceResponse<string>>(fullApiUri + "CreateEvent", codeCamp.ObjectToJson()); return result; }
public ServiceResponse<LoginResult> Login(string email, string password) { var result = new ServiceResponse<LoginResult>(); var member = GetMember(email, password); var loginResult = new LoginResult(); loginResult.LoginFailed = member == null; loginResult.Member = member; result.Data = loginResult; return result; }
private void ClientObjectRelationTypeGet(ServiceResponse<PagedResult<ObjectRelationType>> response, object token) { if (response.Error != null) { ServiceFailed(this, new DataEventArgs<Exception>(response.Error)); return; } foreach (var objectRelationType in response.Body.Results) _objectRelationTypes.Add(objectRelationType); }
public static ServiceResponse Deserialize(XmlReader reader, ServiceResponse serviceResponse) { if (reader.IsStartElement(DTD.Response.TagServiceResponse)) { if (serviceResponse == null) { serviceResponse = new ServiceResponse(); } if (!reader.IsEmptyElement) { reader.ReadStartElement(); do { #region <ERROR> if (reader.IsStartElement(DTD.Response.ServiceResponse.TagError)) { if(int.Parse(reader.GetAttribute(DTD.Error.TagNumber))!=0) { throw XMLErrorSerializer.Deserialize(reader.ReadSubtree()); } else { reader.Skip(); } } #endregion <ERROR> #region <OID> if (reader.IsStartElement(DTD.TagOID)) { serviceResponse.Oid = XMLAdaptorOIDSerializer.Deserialize(reader.ReadSubtree()); } #endregion <OID> #region <Arguments> if (reader.IsStartElement(DTD.Response.ServiceResponse.TagArguments)) { serviceResponse.Arguments = XMLArgumentsSerializer.Deserialize(reader.ReadSubtree()); } #endregion <Arguments> } while (reader.Read()); } else { reader.Skip(); } } else { throw new ArgumentException("Xml Reader don't have the Service.Response in Start Element.", "XmlReader reader"); } return serviceResponse; }
public string AddActivityToRole(string roleId, string activityId) { try { return authorisationManagerServer.AddActivityToRole(roleId, activityId); } catch (Exception ex) { var serviceResponse = new ServiceResponse(ex.Message, ex); var response = Serializer.SerializeToJson(serviceResponse); return response; } }
public string AddRoleToUser(string userId, string roleId) { try { return authorisationManagerServer.AddRoleToUser(userId, roleId); } catch (Exception ex) { var serviceResponse = new ServiceResponse(ex.Message, ex); var response = Serializer.SerializeToJson(serviceResponse); return response; } }
private void ClientLanguageGetCompleted(ServiceResponse<PagedResult<Language>> response, object token) { if(response.Error != null) { ServiceFailed(this, new DataEventArgs<Exception>(response.Error)); return; } foreach (var language in response.Body.Results) _languages.Add(language); Loaded(this, EventArgs.Empty); }
ServiceResponse<Subscriber> ISubscriptionService.Authenticate(ServiceRequest<Subscriber> request) { var output = new ServiceResponse<Subscriber>(); using (var unitOfWork = RepositoryManager<Subscriber>.Instance.CreateWorkUnit()) { try { var repo = new Repository<Subscriber>(unitOfWork.Session); var data = request.Data; var subscribers = repo.FilterBy(x => x.Email == data.Email).ToList(); if (subscribers.Count == 0) { output.Result = Result.LoginFailed; output.Message = "Invalid user name and password"; return output; } foreach (var subscriber in subscribers) { var password = Cryptography.GetMD5Hash(Cryptography.CreateInstance().Decrypt(subscriber.Password)); if (data.Password != password) continue; var guid = Cryptography.GetMD5Hash(Guid.NewGuid().ToString()); output.Data = subscriber; output.Data.Password = guid; output.Result = Result.Successful; ServiceDirectory.CacheService(CacheType.Memory).AddItem(guid, subscriber); return output; } } catch (GenericADOException e) { output.Message = MessageFactory.CreateGenerator(RepositoryType.Postgres).GenerateErrorMessage(e); output.Result = Result.Failure; } catch (Exception e) { _logger.Critical(e.Message, e); output.Message = "Invalid username or password"; output.Result = Result.Failure; } } return output; }
/// <summary> /// ChangeContentRating /// </summary> /// <param name="contentId"></param> /// <param name="contextId"></param> /// <param name="rating"></param> public ServiceResponse ChangeContentRating(int contentId, int contextId, int rating) { ServiceResponse changeContentRatingResponse = new ServiceResponse(); try { SetContext(); _contentManager.ChangeContentRating(contentId,(ContextEnum) contextId, rating); } catch (Exception ex) { HandleError(ex, changeContentRatingResponse); } return changeContentRatingResponse; }
/// <summary> /// ChangeContentLikeDislike /// </summary> /// <param name="contentId"></param> /// <param name="contextId"></param> /// <param name="liked"></param> public ServiceResponse ChangeContentLikeDislike(int contentId, int contextId, bool liked) { ServiceResponse changeContentLikeDislikeResponse = new ServiceResponse(); try { SetContext(); _contentManager.ChangeContentLikeDislike(contentId,(ContextEnum)contextId, liked); } catch (Exception ex) { HandleError(ex, changeContentLikeDislikeResponse); } return changeContentLikeDislikeResponse; }
/// <summary> /// CheckECollabroSetup /// </summary> /// <param name="serviceRequest"></param> /// <returns></returns> public ServiceResponse<bool> CheckEcollabroSetup() { ServiceResponse<bool> checkECollabroSetupResponse = new ServiceResponse<bool>(); try { checkECollabroSetupResponse.Result = _setupManager.IsEcollabroSetupReady(); } catch (Exception ex) { HandleError(ex, checkECollabroSetupResponse); } return checkECollabroSetupResponse; }
/// <summary> /// DeleteSiteCollectionAdmin /// </summary> /// <returns></returns> public ServiceResponse DeleteSiteCollectionAdmin(int userId) { ServiceResponse siteCollectionAdminResponse = new ServiceResponse(); try { SetContext(); _setupManager.DeleteSiteCollectionAdmin(userId); } catch (Exception ex) { HandleError(ex, siteCollectionAdminResponse); } return siteCollectionAdminResponse; }
/// <summary> /// LogError /// </summary> /// <param name="logException"></param> /// <returns></returns> public ServiceResponse LogError(string logException) { ServiceResponse logExceptionResponse = new ServiceResponse(); try { log.Error(logException); } catch (Exception ex) { HandleError(ex, logExceptionResponse); // Can't Log exception } return logExceptionResponse; }
ServiceResponse<IList<BudgetItem>> IBudgetService.BudgetItemList(String budgetId) { var output = new ServiceResponse<IList<BudgetItem>>(); using (var unitOfWork = RepositoryManager<BudgetItem>.Instance.CreateWorkUnit()) { try { var repo = new Repository<BudgetItem>(unitOfWork.Session); List<BudgetItem> result; result = String.IsNullOrEmpty(budgetId) ? repo.FilterBy(x => x.Subscriber.Id == _subscriber.Id).ToList() : repo.FilterBy(x => (x.Subscriber.Id == _subscriber.Id && x.Budget.Id == budgetId)).ToList(); unitOfWork.Commit(); foreach (var item in result) { if (item.ReceiptList == null) { continue; } foreach (var receipt in item.ReceiptList.Where(receipt => !receipt.BudgetPeriod.EndDate.HasValue)) { item.CurrentPeriod = receipt.BudgetPeriod; } } output.Data = result; output.Result = Result.Successful; } catch (GenericADOException e) { output.Message = MessageFactory.CreateGenerator(RepositoryType.Postgres).GenerateErrorMessage(e); _logger.Critical(output.Message, e); output.Result = Result.Failure; } catch (Exception e) { _logger.Critical(e.Message, e); } } return output; }
public ServiceResponse<bool> CanCompleteTask(int taskID) { var result = new ServiceResponse<bool>(); try { int incompleteChildTasks = _taskRepo.CountIncompleteChildren(taskID); var canCompleteTask = incompleteChildTasks == 0; } catch (Exception ex) { result.ErrorMessage = ex.ToString(); result.Success = false; } return result; }
public ServiceResponse<IList<SuspenderItem>> SetSuspenderList(IList<SuspenderItem> items) { var response = new ServiceResponse<IList<SuspenderItem>>(); try { throw new NotImplementedException(); } catch (Exception e) { response.Success = false; response.Timestamp = DateTime.Now; response.Error = e.Message; } return response; }
public async Task <IActionResult> List() { ServiceResponse <List <CustomerDto> > customerResponse = await _customerService.List(); return(Ok(customerResponse.Resource)); }
public Response(ServiceResponse response, Func<ServiceResponse, T> parser) { _response = response; _contentParser = parser; _parsedContent = default; }
protected void PostResponse(string data) { ServiceResponse.Write(data); EndResponse(); }
public ServiceResponse BusinessAddressLookup(string accountId) { ServiceResponse response = businessService.GetBusinessModelByAccountId(this.CurrentUser, accountId); return(response); }
public JsonResult AddHunting([FromBody] HuntingServiceModel hunt) { var addResult = hunting.AddHunting(hunt); return(new JsonResult(ServiceResponse <string> .Create(addResult.IsSuccess, addResult.Payload, addResult.Code))); }
public JsonResult DeleteQuarry(Guid id) { var deleteResult = hunting.DeleteQuarry(id); return(new JsonResult(ServiceResponse <string> .Create(deleteResult.IsSuccess, deleteResult.Payload, deleteResult.Code))); }
public JsonResult AddQuarry([FromBody] QuarryServiceModel quarry) { var addResult = hunting.AddQuarry(quarry); return(new JsonResult(ServiceResponse <string> .Create(addResult.IsSuccess, addResult.Payload, addResult.Code))); }
public async Task <ServiceResponse <GetCommentDto> > Add(AddCommentDto addCommentDto) { ServiceResponse <GetCommentDto> response = new ServiceResponse <GetCommentDto>(); if (addCommentDto == null) { response.Data = null; response.Message = "There is no data"; response.Success = false; return(response); } User user = await _context.Users.FirstOrDefaultAsync(u => u.Id == GetUserId()); Submission submission = await _context.Submissions.Include(s => s.AffiliatedAssignment) .Include(s => s.Comments) .FirstOrDefaultAsync(s => s.Id == addCommentDto.CommentedSubmissionId); if (submission == null) { response.Data = null; response.Message = "There is no comment with this Id"; response.Success = false; return(response); } if (submission.Comments.Any(c => c.CommentedUserId == GetUserId())) { response.Data = null; response.Message = "You already commented on this submission"; response.Success = false; return(response); } //user comment Course course = await _context.Courses.Include(c => c.Instructors).FirstOrDefaultAsync(c => c.Id == submission.AffiliatedAssignment.AfilliatedCourseId); if (course == null) { response.Data = null; response.Message = "There is a mistake about course"; response.Success = false; return(response); } //&& user.UserType == UserTypeClass.Student && submission.AffiliatedAssignment if (!course.Instructors.Any(cu => cu.UserId == user.Id) && !submission.AffiliatedAssignment.CanBeGradedByStudents) { response.Data = null; response.Message = "You are not authorized to make comment"; response.Success = false; return(response); } Comment comment = new Comment { CommentedSubmissionId = addCommentDto.CommentedSubmissionId, CommentText = addCommentDto.CommentText, CreatedAt = DateTime.Now, CommentedUserId = user.Id, FilePath = "", Grade = addCommentDto.Grade, MaxGrade = addCommentDto.MaxGrade, FileAttachmentAvailability = false }; await _context.Comments.AddAsync(comment); await _context.SaveChangesAsync(); response.Data = _mapper.Map <GetCommentDto>(comment); response.Data.FileEndpoint = "Comment/File/" + comment.Id; response.Data.FileName = comment.FileAttachmentAvailability ? comment.FilePath.Split('/').Last() : ""; return(response); }
public async Task <ServiceResponse <ValidateUserResponse> > ValidateUser(ValidateUserRequest validateUserRequest) { _logger.Information("Call ValidateUserManager : ValidateUser"); var response = new ServiceResponse <ValidateUserResponse> { IsSuccess = true, TokenStatus = TokenStatus.NotRequired }; using (IDalContext dalContext = new DalContext(_connectionStrings.HackConnection)) { var dalRequest = new ValidateDalRequest { EmailId = validateUserRequest.EmailId }; var dalResponse = await _validateUser.ValidateUser(dalContext.DbConnection, dalRequest); //Check if success returned from DB if (!dalResponse.IsSuccess || dalResponse.UserId <= 0) { response.Data = new ValidateUserResponse { SecurityToken = string.Empty, }; response.TokenStatus = dalResponse.TokenStatus; response.IsSuccess = false; response.Message = dalResponse.ErrorMessage ?? ApiMessages.InternalError; } else { response.IsSuccess = true; //Encrypt token var encryptedToken = Cryptology.EncryptString(string.Format("{0}##{1}##{2}", Utilities.CreateShortGuid(), dalResponse.UserId, DateTime.UtcNow.AddHours(Constants.ValidTokenDuration).ToString(ServiceConstants.DateFormat)), _logger); try { response.IsSuccess = true; { response.Data = new ValidateUserResponse { SecurityToken = encryptedToken, }; response.TokenStatus = dalResponse.TokenStatus; response.IsSuccess = dalResponse.IsSuccess; } } catch (SqlException ex) { //Write Log for exception message _logger.Error(ex.Message); response.IsSuccess = false; response.Message = ServiceConstants.ErrorCodes.ContainsKey(ex.Number) ? ServiceConstants.ErrorCodes[ex.Number] : ApiMessages.InternalError; } catch (Exception ex) { _logger.Error("Error : {ex}", ex); response.IsSuccess = false; response.Message = ApiMessages.InternalError; } } } return(response); }
public async Task <ServiceResult> SendMessage(Message form)// public ServiceResult SendMessage(Message form) { if (form == null) { return(ServiceResponse.Error("No form was posted to the server.")); } form.DateSent = DateTime.UtcNow; bool isValidFormat = Validator.IsValidEmailFormat(form.SentFrom); if (string.IsNullOrWhiteSpace(form.SentFrom) || isValidFormat == false) { ServiceResponse.Error("You must provide a valid email address."); } if (string.IsNullOrWhiteSpace(form.Comment)) { ServiceResponse.Error("You must provide a message."); } NetworkHelper network = new NetworkHelper(); string ipAddress = network.GetClientIpAddress(this.Request); EmailLog emailLog = new EmailLog(); emailLog.Message = form.Comment + "<br/><br/><br/>Message Key:" + emailLog.UUID; emailLog.Subject = form.Subject; emailLog.EmailFrom = form.SentFrom; emailLog.UUIDType += "." + form.Type; if (form.Type?.ToLower() != "contactus") { emailLog.EmailTo = Globals.Application.AppSetting("SiteEmail"); } emailLog.DateCreated = DateTime.UtcNow; emailLog.IpAddress = ipAddress; emailLog.Status = "not_sent"; if (CurrentUser != null) { emailLog.CreatedBy = CurrentUser.UUID; emailLog.AccountUUID = CurrentUser.AccountUUID; } else { emailLog.CreatedBy = "ContactUsForm"; emailLog.AccountUUID = "ContactUsForm"; } EmailLogManager emailLogManager = new EmailLogManager(Globals.DBConnectionKey); if (emailLogManager.Insert(emailLog).Code == 500) { return(ServiceResponse.Error("Failed to save the email. Try again later.")); } EmailSettings settings = new EmailSettings(); settings.EncryptionKey = Globals.Application.AppSetting("AppKey"); settings.HostPassword = Globals.Application.AppSetting("EmailHostPassword"); settings.HostUser = Globals.Application.AppSetting("EmailHostUser"); settings.MailHost = Globals.Application.AppSetting("MailHost"); settings.MailPort = StringEx.ConvertTo <int>(Globals.Application.AppSetting("MailPort")); settings.SiteDomain = Globals.Application.AppSetting("SiteDomain"); settings.SiteEmail = Globals.Application.AppSetting("SiteEmail"); settings.UseSSL = StringEx.ConvertTo <bool>(Globals.Application.AppSetting("UseSSL")); MailAddress ma = new MailAddress(form.SentFrom, form.SentFrom); MailMessage mail = new MailMessage(); mail.From = ma; mail.ReplyToList.Add(ma); mail.To.Add(emailLog.EmailTo); mail.Subject = emailLog.Subject; mail.Body = emailLog.Message + "<br/><br/><br/>IP:" + ipAddress; mail.IsBodyHtml = true; SMTP svc = new SMTP(Globals.DBConnectionKey, settings); return(await svc.SendMailAsync(mail)); }
public async Task <ServiceResponse <List <UserInformation> > > AddUser(UserInformation newUser) { ServiceResponse <List <UserInformation> > serviceResponse = new ServiceResponse <List <UserInformation> >(); if (UsernameExists(newUser.Username) || EmailExists(newUser.Email)) { serviceResponse.Success = false; return(serviceResponse); } else { UserBalance userBalance = new UserBalance(); UserAchievement userAchievement = new UserAchievement(); _context.UserInfo.Add(newUser); _context.UserBalance.Add(userBalance); await _context.SaveChangesAsync(); userBalance.user_id = (_context.UserInfo.Where(e => e.Email == newUser.Email && e.Password == newUser.Password).FirstOrDefault()).ID.ToString(); _context.UserBalance.Add(userBalance); userAchievement.userID = (_context.UserInfo.Where(e => e.Email == newUser.Email && e.Password == newUser.Password).FirstOrDefault()).ID; _context.UserAchievement.Add(new UserAchievement { Nr = 1, Name = "Register", Description = "Create an account", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 2, Name = "Baby Steps", Description = "Create your first item to save for", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 3, Name = "Profiting", Description = "Have more income than expenses", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 4, Name = "Gains", Description = "Add some income", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 5, Name = "Losses", Description = "Add some expenses", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 6, Name = "Getting Started", Description = "Have three saving goals", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 7, Name = "Completed!", Description = "Complete one saving goal", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 8, Name = "Progress", Description = "Complete three saving goals", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 9, Name = "Keep going", Description = "Complete five saving goals", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 10, Name = "Nice job", Description = "Complete ten saving goals", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 11, Name = "Great job", Description = "Complete twenty five saving goals", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 12, Name = "Awesome", Description = "Complete fifty saving goals", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 13, Name = "Incredible", Description = "Complete a hundred saving goals", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 14, Name = "Profiting 2x", Description = "Have twice as much income than expenses", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 15, Name = "Making Cash", Description = "Have five times as much income than expenses", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 16, Name = "Big Dreams", Description = "Have ten saving goals submitted", Status = 0, Score = 10, userID = userAchievement.userID }); _context.UserAchievement.Add(new UserAchievement { Nr = 17, Name = "Only Wishes", Description = "Have fifteen saving goals submitted", Status = 0, Score = 10, userID = userAchievement.userID }); await _context.SaveChangesAsync(); serviceResponse.Data = await _context.UserInfo.ToListAsync(); return(serviceResponse); } }
public abstract TResult Deserialize(ServiceResponse xmlStream);
/// <summary> /// Updates the service status. /// </summary> /// <param name="ServiceName">Name of the service.</param> /// <param name="MachineName">Name of the machine.</param> /// <param name="Status">The status.</param> /// <returns></returns> public ServiceResponse UpdateServiceStatus(string ServiceName, string MachineName, int Status, bool isWebService = false) { Logger.logEvent(LogLevel.INFO, "Entered UpdateServiceStatus"); ServiceResponse objServiceResponse = new ServiceResponse(); objServiceResponse.ServiceName = ServiceName; objServiceResponse.MacineName = MachineName; objServiceResponse.IsWebService = isWebService; objServiceResponse.Result = false; try { ServiceController _service = new ServiceController(ServiceName, MachineName); if (!isWebService) { //if(_service) switch (Status) { case 4: if (_service.Status != ServiceControllerStatus.Running) { _service.Start(); } objServiceResponse.Result = true; break; case 1: if (_service.Status != ServiceControllerStatus.Stopped) { if (_service.CanStop) { _service.Stop(); objServiceResponse.Result = true; } else { objServiceResponse.ErrorMessage = "Cannot Stop service, it is an Unstoppable Service"; Logger.logEvent(LogLevel.ERROR, "Cannot Stop service, it is an Unstoppable Service --> " + _service.DisplayName); } } break; case 7: if (_service.Status != ServiceControllerStatus.Paused) { if (_service.CanPauseAndContinue) { _service.Pause(); objServiceResponse.Result = true; } else { objServiceResponse.ErrorMessage = "Cannot Pause service"; Logger.logEvent(LogLevel.ERROR, "Cannot Pause service --> " + _service.DisplayName); } } break; case 10: if (_service.CanStop) { _service.Stop(); _service.Start(); objServiceResponse.Result = true; } else { objServiceResponse.ErrorMessage = "Cannot Restart service, it is an Unstoppable Service"; Logger.logEvent(LogLevel.ERROR, "Cannot Restart service --> " + _service.DisplayName); } break; default: objServiceResponse.ErrorMessage = "Invalid Status Command"; Logger.logEvent(LogLevel.ERROR, "Error in ServiceRepository.UpdateServiceStatus --> " + "Invalid Status Command"); break; } } else { var server = ServerManager.OpenRemote(MachineName); var site = server.Sites.FirstOrDefault(s => s.Name == ServiceName); switch (Status) { case 4: if (site.State != ObjectState.Started || site.State != ObjectState.Starting) { site.Start(); } objServiceResponse.Result = true; break; case 1: case 7: if (site.State != ObjectState.Stopped || site.State != ObjectState.Stopping) { site.Stop(); objServiceResponse.Result = true; } break; case 10: site.Stop(); site.Start(); objServiceResponse.Result = true; break; default: objServiceResponse.ErrorMessage = "Invalid Status Command"; Logger.logEvent(LogLevel.ERROR, "Error in ServiceRepository.UpdateServiceStatus --> " + "Invalid Status Command"); break; } } } catch (Exception ex) { objServiceResponse.ErrorMessage = ex.Message; Logger.logEvent(LogLevel.ERROR, "Error in ServiceRepository.UpdateServiceStatus --> " + ex.Message); objServiceResponse.Result = false; } return(objServiceResponse); }
public async Task <ServiceResponse <PeerGradeInfoDto> > GetPeerGradeByUsersAndGroup(GetPeerGradeDto getPeerGradeDto) { ServiceResponse <PeerGradeInfoDto> response = new ServiceResponse <PeerGradeInfoDto>(); User user = await _context.Users .Include(u => u.InstructedCourses) .FirstOrDefaultAsync(u => u.Id == GetUserId()); ProjectGroup projectGroup = await _context.ProjectGroups.Include(g => g.AffiliatedCourse).ThenInclude(c => c.PeerGradeAssignment) .Include(g => g.GroupMembers) .FirstOrDefaultAsync(rg => rg.Id == getPeerGradeDto.ProjectGroupId); if (projectGroup == null) { response.Data = null; response.Message = "There is no project group with this id"; response.Success = false; return(response); } if (!IsUserInGroup(projectGroup, getPeerGradeDto.ReviewerId)) { response.Data = null; response.Message = "There is no user with reviewerId in group"; response.Success = false; return(response); } if (!IsUserInGroup(projectGroup, getPeerGradeDto.RevieweeId)) { response.Data = null; response.Message = "There is no user with revieweeId in group"; response.Success = false; return(response); } PeerGradeAssignment pga = await _context.PeerGradeAssignments .FirstOrDefaultAsync(pga => pga.CourseId == projectGroup.AffiliatedCourseId); if (pga == null) { response.Data = null; response.Message = "Course doesn't have a peer grade assignment"; response.Success = false; return(response); } if (user == null || (!doesUserInstruct(user, projectGroup.AffiliatedCourseId) && user.Id != getPeerGradeDto.ReviewerId)) { response.Data = null; response.Message = "You are not authorized to see this peer grade"; response.Success = false; return(response); } PeerGrade peerGrade = await _context.PeerGrades .FirstOrDefaultAsync(pg => pg.ReviewerId == getPeerGradeDto.ReviewerId && pg.RevieweeId == getPeerGradeDto.RevieweeId && pg.ProjectGroupId == getPeerGradeDto.ProjectGroupId); if (peerGrade == null) { response.Data = null; response.Message = "There is no such peer grade"; response.Success = false; return(response); } PeerGradeInfoDto dto = new PeerGradeInfoDto { Id = peerGrade.Id, ProjectGroupId = peerGrade.ProjectGroupId, ReviewerId = peerGrade.ReviewerId, RevieweeId = peerGrade.RevieweeId, MaxGrade = peerGrade.MaxGrade, Grade = peerGrade.Grade, Comment = peerGrade.Comment, LastEdited = peerGrade.LastEdited }; response.Data = dto; response.Message = "Success"; response.Success = true; return(response); }
public async Task <ServiceResponse <AddPeerGradeDto> > AddPeerGrade(AddPeerGradeDto addPeerGradeDto) { ServiceResponse <AddPeerGradeDto> response = new ServiceResponse <AddPeerGradeDto>(); User user = await _context.Users.Include(u => u.ProjectGroups) .ThenInclude(g => g.ProjectGroup) .FirstOrDefaultAsync(u => u.Id == GetUserId()); ProjectGroup projectGroup = await _context.ProjectGroups .Include(g => g.AffiliatedCourse) .Include(g => g.GroupMembers) .FirstOrDefaultAsync(rg => rg.Id == addPeerGradeDto.ProjectGroupId); if (projectGroup == null) { response.Data = null; response.Message = "There is no project group with this id"; response.Success = false; return(response); } if (!IsUserInGroup(projectGroup, GetUserId())) { response.Data = null; response.Message = "You are not in this group"; response.Success = false; return(response); } if (!IsUserInGroup(projectGroup, addPeerGradeDto.RevieweeId)) { response.Data = null; response.Message = "You are not in the same group with the reviewee "; response.Success = false; return(response); } PeerGradeAssignment pga = await _context.PeerGradeAssignments.Include(pg => pg.PeerGrades) .FirstOrDefaultAsync(pga => pga.CourseId == projectGroup.AffiliatedCourseId); if (pga == null) { response.Data = null; response.Message = "Course doesn't have a peer grade assignment"; response.Success = false; return(response); } if (pga.DueDate < addPeerGradeDto.LastEdited) { response.Data = null; response.Message = "Due date has passed for the peer grade assignment"; response.Success = false; return(response); } PeerGrade peerGrade = await _context.PeerGrades .FirstOrDefaultAsync(pg => pg.ReviewerId == GetUserId() && pg.RevieweeId == addPeerGradeDto.RevieweeId && pg.ProjectGroupId == addPeerGradeDto.ProjectGroupId); if (peerGrade != null) { response.Data = null; response.Message = "You have already peer graded this group member"; response.Success = false; return(response); } if (pga.MaxGrade < addPeerGradeDto.Grade) { response.Data = null; response.Message = "Grade should be less than or equal to the max grade"; response.Success = false; return(response); } PeerGrade createdPeerGrade = new PeerGrade { MaxGrade = pga.MaxGrade, Grade = addPeerGradeDto.Grade, Comment = addPeerGradeDto.Comment, LastEdited = addPeerGradeDto.LastEdited, ProjectGroupId = addPeerGradeDto.ProjectGroupId, ReviewerId = GetUserId(), RevieweeId = addPeerGradeDto.RevieweeId }; pga.PeerGrades.Add(createdPeerGrade); _context.ProjectGroups.Update(projectGroup); _context.PeerGrades.Add(createdPeerGrade); await _context.SaveChangesAsync(); response.Data = addPeerGradeDto; response.Message = "You successfully entered peer grade"; response.Success = true; return(response); }
/// <summary> /// Get values in appparameter table on db /// </summary> /// <param name="parameterName">parameter key value</param> /// <returns>parameter value</returns> public string GetParameterValue(string parameterName) { if (base.InstitutionId == 0) { base.InstitutionId = 1; } if (conStr != "") { List <IDataParameter> paramlist = new List <IDataParameter>(); paramlist.Add(new CustomParameter { ParameterName = "parametername", Value = parameterName }); paramlist.Add(new CustomParameter { ParameterName = "institutionid", Value = base.InstitutionId }); List <AppParameter> res = qm.GetQueryResult <AppParameter>("GetParameter", paramlist); if (res.Count > 0) { return(res[0].ParameterValue); } throw new Exception("Parameter has not been found on db!"); } else { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "Api/app/GetParameter?parameterName=" + parameterName + "&institutionId=" + base.InstitutionId); request.Headers.Add("Authorization", this.accesskey); WebResponse response = request.GetResponse(); Stream responseStream = response.GetResponseStream(); ServiceResponse <AppParameter> sr = JsonHelper.Instance.DeserializeFromStream <ServiceResponse <AppParameter> >(responseStream); if (sr.ResponseCode == 1) { if (sr.ResponseObject != null) { return(sr.ResponseObject.ParameterValue); } } else { // Error Message :Exception while reading from stream //Inner Exception :System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. --->System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond // at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) // at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) // -- - End of inner exception stack trace-- - // at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) // at Npgsql.ReadBuffer.Ensure(Int32 count, Boolean dontBreakOnTimeouts) //Stack Trace : at Npgsql.ReadBuffer.Ensure(Int32 count, Boolean dontBreakOnTimeouts) // at Npgsql.NpgsqlConnector.DoReadMessage(DataRowLoadingMode dataRowLoadingMode, Boolean isPrependedMessage) // at Npgsql.NpgsqlConnector.ReadMessageWithPrepended(DataRowLoadingMode dataRowLoadingMode) // at Npgsql.NpgsqlConnector.ReadExpecting[T]() // at Npgsql.NpgsqlDataReader.NextResultInternal() // at Npgsql.NpgsqlDataReader.NextResult() // at Npgsql.NpgsqlCommand.Execute(CommandBehavior behavior) // at Npgsql.NpgsqlCommand.ExecuteDbDataReaderInternal(CommandBehavior behavior) // at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior) // at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) // at Dapper.SqlMapper.< QueryImpl > d__11`1.MoveNext() // at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) // at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) // at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) // at Royal.Operation.Business.DB.QueryManager.GetQueryText(String queryName) in C:\GIT\feedframework\Royal.Operation\Business\DB\QueryManager.cs:line 57 // at Royal.Operation.Business.DB.QueryManager.GetQueryResult[T](String queryName, List`1 cparams) in C:\GIT\feedframework\Royal.Operation\Business\DB\QueryManager.cs:line 123 // at Royal.WebApi.Controllers.AppController.GetParameter(String parameterName) in C:\GIT\feedframework\Royal.WebApi\Controllers\AppController.cs:line 162 throw new Exception(sr.ResponseMessage); } throw new Exception("Parameter has not been found on db!"); } }
public JsonResult GetQuarry(Guid id) { var queryResult = hunting.GetQuarry(id); return(new JsonResult(ServiceResponse <IEnumerable <Quarry> > .Create(queryResult.IsSuccess, queryResult.Payload, queryResult.Code))); }
public ServiceResponse UserRegistration(UserModel model) { ServiceResponse response = new ServiceResponse(); model.IsRegistering = true; // Lookup account by business name, state, postal code BusinessModel identifiedBusiness = SearchForBusiness(model); // In order to prevent duplicates we will lookup the business by name, state, postal code // and if it exists return back the business and send an email to the super user that a user // wants to register if (identifiedBusiness != null) { model.Business = identifiedBusiness; model.ExistingBusiness = ExistingBusinessEnum.Existing; } response = userService.PostModel(this.CurrentUser, model); model = response.Model as UserModel; if (response.IsOK) { if (model.IsRegistering) { businessService.SetupDefaultPermission(this.CurrentUser, model.Business); userService.SetupDefaultPermissions(this.CurrentUser, model); try { var emailModel = userService.GetUserRegistrationEmailModel(model).Model as SendEmailModel; emailModel.Subject = "New Project Office Registration"; emailModel.RenderTextVersion = true; //emailModel.BodyTextVersion = RenderView(this, "SendEmailUserRegistration", emailModel); //emailModel.BodyTextVersion = MvcAccountController.RenderView(MvcAccountController, "SendEmailUserRegistration", emailModel); //GET var serializedModel = JsonConvert.SerializeObject(emailModel); var client = new HttpClient(); var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority); var result = client.GetAsync(baseUrl + "/ViewRender/Render?ViewName=UserRegistrationEmailTemplate&SerializedModel=" + serializedModel).Result; //var result = client.GetAsync(baseUrl + "/Account/Render?ViewName=SendEmailUserRegistration&SerializedModel=" + serializedModel).Result; //POST //ViewRenderModel viewRenderModel = new ViewRenderModel //{ // ViewName = "SendEmailUserRegistration", // ViewModel = emailModel //}; //var result = client.PostAsJsonAsync(baseUrl + "/ViewRender/Render", viewRenderModel).Result; emailModel.RenderTextVersion = false; //emailModel.BodyHtmlVersion = RenderView(this, "SendEmailUserRegistration", emailModel); var emailservice = new EmailServices(); emailservice.SendEmail(emailModel); } catch (Exception e) { Utilities.ErrorLog(e); } } //return PartialView("RegistrationAcknowledgement", "Account"); } //var userModel = response.Model as UserModel; //return PartialView("UserRegistration", this.ServiceResponse.Model); return(response); }
public JsonResult UpdateQuarry([FromBody] QuarryServiceModel quarry) { var updateResult = hunting.UpdateQuarry(quarry); return(new JsonResult(ServiceResponse <string> .Create(updateResult.IsSuccess, updateResult.Payload, updateResult.Code))); }
private static Task <ServiceResponse <T> > CreateResponse <T>(T result) { var response = new ServiceResponse <T>(result, EndpointStatus.Alive); return(Task.FromResult(response)); }
public async Task <IHttpActionResult> UpdateProfile(UserProfileVM model) { StringBuilder traceLog = null; ServiceResponse <UserProfileVM> objResponse = null; try { traceLog = new StringBuilder(); traceLog.AppendLine("Start: UpdateProfile() Request Data:-FirstName-" + model.FirstName + ",LastName-" + model.LastName + ",EmailId-" + model.EmailId + ",UserType-" + model.UserType + ",UserId-" + model.UserId + ",PicBase64String-" + model.PicBase64String + ",PicExtension-" + model.PicExtension + ",PicName-" + model.PicName); objResponse = new ServiceResponse <UserProfileVM>(); Credentials objCred = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name); // Update Profile Pic if (!string.IsNullOrWhiteSpace(model.PicBase64String)) { string root = HttpContext.Current.Server.MapPath("~/images/profilepic"); var bytes = Convert.FromBase64String(model.PicBase64String); string picName = Guid.NewGuid().ToString() + ConstantHelper.constUnderscore + model.PicName + "." + model.PicExtension; using (var imageFile = new FileStream(root + ConstantHelper.constDoubleBackSlash + picName, FileMode.Create)) { imageFile.Write(bytes, 0, bytes.Length); imageFile.Flush(); if (imageFile != null) { imageFile.Dispose(); } } model.PicName = picName; ProfileBL.UpdateProfilePic(model.UserId, model.UserType, picName); } bool IsEmailExist = await UseresBL.IsEmailExist(model.EmailId, objCred.UserType, objCred.UserId); if (IsEmailExist) { objResponse.IsResultTrue = false; objResponse.ErrorMessage = Message.EmailAlreadyExist; } else { objResponse.jsonData = await ProfileBL.UpdateUserProfile(model, objCred.Id); if (objResponse.jsonData.ZipcodeNotExist) { objResponse.IsResultTrue = false; objResponse.ErrorMessage = Message.ZipCodeNotExist; } else { objResponse.IsResultTrue = true; } } return(Ok(objResponse)); } catch (Exception ex) { LogManager.LogManagerInstance.WriteErrorLog(ex); return(BadRequest(ex.Message)); } finally { traceLog.AppendLine("End:UpdateProfile() Response Result Ststus-" + objResponse.IsResultTrue + ",ErrorMessage-" + objResponse.ErrorMessage + "Updated DateTime-" + DateTime.Now.ToLongDateString()); LogManager.LogManagerInstance.WriteTraceLog(traceLog); traceLog = null; } }
public Task <ServiceResponse <IEnumerable <ResultFormatInformation> > > GetResultFormatsAsync() { var response = ServiceResponse.Create(s_formats); return(Task.FromResult(response)); }
public ServiceResponse UserRegistration() { ServiceResponse response = userService.GetUserModelForRegistering(); return(response); }
public async Task <ServiceResponse <Post> > CreatePost(AddPostDto newPost) { ServiceResponse <Post> response = new ServiceResponse <Post>(); try { var author = await _authorService.FindAuthorById(newPost.AuthorId); var post = new Post() { Title = newPost.Title, Summary = newPost.Summary, Body = newPost.Body, LastModified = newPost.LastModified }; _context.Posts.Add(post); post.Author = author; await _context.SaveChangesAsync(); //now checks which category has been specified if (!string.IsNullOrEmpty(newPost.Category)) { ////finds the category object that corresponds to the category name received ////just one category is added from the frontend var query = await _categoryService.FindCategoryByName(newPost.Category); if (!query.Success) { response.Message = "There has been a problem retrieving the category"; } var category = query.Data.FirstOrDefault(); var postCategory = new PostCategories { Post = post, Category = category }; _context.PostCategories.Add(postCategory); } else { // //assign the default category as General that is the category with Id 1 var category = await _context.Categories.Where(c => c.CategoryId == 1) .ToListAsync(); var postCategory = new PostCategories { Post = post, Category = category.FirstOrDefault() }; _context.PostCategories.Add(postCategory); } await _context.SaveChangesAsync(); response.Data = _mapper.Map <Post>(newPost); } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return(response); }
public Response(ServiceResponse response, T parsed) { _response = response; _contentParser = null; _parsedContent = parsed; }
public async Task <ServiceResponse <PeerGradeInfoDto> > EditPeerGrade(EditPeerGradeDto editPeerGradeDto) { ServiceResponse <PeerGradeInfoDto> response = new ServiceResponse <PeerGradeInfoDto>(); User user = await _context.Users.Include(u => u.ProjectGroups) .ThenInclude(g => g.ProjectGroup) .FirstOrDefaultAsync(u => u.Id == GetUserId()); PeerGrade peerGrade = await _context.PeerGrades.FirstOrDefaultAsync(pg => pg.Id == editPeerGradeDto.Id); if (peerGrade == null) { response.Data = null; response.Message = "There is no peer grade with this Id."; response.Success = false; return(response); } if (peerGrade.ReviewerId != user.Id) { response.Data = null; response.Message = "You are not authorized to change this peer grade"; response.Success = false; return(response); } ProjectGroup projectGroup = await _context.ProjectGroups .Include(g => g.GroupMembers) .FirstOrDefaultAsync(rg => rg.Id == peerGrade.ProjectGroupId); PeerGradeAssignment pga = await _context.PeerGradeAssignments .FirstOrDefaultAsync(pga => pga.CourseId == projectGroup.AffiliatedCourseId); if (pga.DueDate < editPeerGradeDto.LastEdited) { response.Data = null; response.Message = "Due date has passed for the peer grade assignment"; response.Success = false; return(response); } if (peerGrade.MaxGrade < editPeerGradeDto.Grade) { response.Data = null; response.Message = "Grade should be less than or equal to the max grade"; response.Success = false; return(response); } peerGrade.Grade = editPeerGradeDto.Grade; peerGrade.Comment = editPeerGradeDto.Comment; _context.PeerGrades.Update(peerGrade); await _context.SaveChangesAsync(); PeerGradeInfoDto peerGradeInfoDto = new PeerGradeInfoDto { Id = peerGrade.Id, ProjectGroupId = peerGrade.ProjectGroupId, ReviewerId = peerGrade.ReviewerId, RevieweeId = peerGrade.RevieweeId, MaxGrade = peerGrade.MaxGrade, Grade = peerGrade.Grade, Comment = peerGrade.Comment, LastEdited = peerGrade.LastEdited }; response.Data = peerGradeInfoDto; response.Message = "You successfully entered peer grade"; response.Success = true; return(response); }
public async Task <ServiceResponse <PagedList <CityView> > > GetCitys(CustomPagingRequest request) { var response = new ServiceResponse <PagedList <CityView> >(); try { var query = (from x in _context.Citys join y in _context.State on x.State equals y.Id join z in _context.Countries on y.Country equals z.Id join c in _context.Users on x.createdBy equals c.id join m in _context.Users on x.modifiedBy equals m.id into modifies from m in modifies.DefaultIfEmpty() select new CityView() { modifiedBy = x.modifiedBy, countryName = z.Name, createdBy = x.createdBy, createdByName = Common.GetFullName(c), createdDate = x.createdDate, modifiedByName = Common.GetFullName(m), modifiedDate = x.modifiedDate, stateName = y.Name, Name = x.Name, Id = x.Id, State = x.State, country = y.Country }).AsQueryable(); switch (request.sort) { case "countryName": query = (request.sortOrder == "Descending" ? query.OrderByDescending(x => x.country) : query.OrderBy(x => x.country)); break; case "modifiedBy": query = (request.sortOrder == "Descending" ? query.OrderByDescending(x => x.modifiedBy) : query.OrderBy(x => x.modifiedBy)); break; case "createdBy": query = (request.sortOrder == "Descending" ? query.OrderByDescending(x => x.createdBy) : query.OrderBy(x => x.createdBy)); break; case "createdDate": query = (request.sortOrder == "Descending" ? query.OrderByDescending(x => x.createdDate) : query.OrderBy(x => x.createdDate)); break; case "modifiedName": query = (request.sortOrder == "Descending" ? query.OrderByDescending(x => x.modifiedBy) : query.OrderBy(x => x.modifiedBy)); break; case "modifiedDate": query = (request.sortOrder == "Descending" ? query.OrderByDescending(x => x.modifiedDate) : query.OrderBy(x => x.modifiedDate)); break; case "id": query = (request.sortOrder == "Descending" ? query.OrderByDescending(x => x.Id) : query.OrderBy(x => x.Id)); break; case "stateName": query = (request.sortOrder == "Descending" ? query.OrderByDescending(x => x.State) : query.OrderBy(x => x.State)); break; default: break; } response.Data = new PagedList <CityView>( query, request); response.Success = true; response.Message = "Data Retrived"; } catch (Exception ex) { response.Success = false; response.Message = await CustomLog.Log(ex, _context); } return(response); }
int serviceId = 0; // Convert.ToInt16(ConfigurationManager.AppSettings["ServiceID"]); // EtlTimer sync = new EtlTimer(); // Version 2.0 /// ************************************************************************************** /// Version 2.0 Feb13-17 /// Perform Directory File search process when task time is due /// Look for existing files in the NIB new files folder /// Same method is used in the WindowsService version.... /// -------------------------------------------------------------------------------------- //public void FileSearch(object e, EtlTimer sync) /// NOT USED IN Version 3.0 //{ // if (serviceId == 0) // { // //serviceId = Convert.ToInt16(ConfigurationManager.AppSettings["ServiceID"]); ; // //sync = wtf.getImportControl(serviceId); // serviceId = sync.MwEtlTimerId; // } // List<string> li = new List<string>(); // // // wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (NBI FileSearch) Start Directory scanning. for " + sync.ServiceName + "."); // // // //li.Add(ConfigurationManager.AppSettings["NewFilesDirectory"].ToString()); // C:\\ImportNIBData_xml // li.Add(sync.InputFileFolder); // if (li.Count == 0) // { // wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (NBI FileSearch) No Folder to process. for " + sync.ServiceName); // } // foreach (string path in li) // { // if (File.Exists(path)) // { // This path is a file // ProcessFile(path, sync); // } // else if (Directory.Exists(path)) // { // This path is a directory // ProcessDirectory(path, sync); // } // else // { // Invalid File or Directory exit // wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, "(NBI FileSearch) <" + path + " > is not a valid file or directory."); // } // } // wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (FileSearch) " + sync.ServiceName + " Files read: " + FilesRead); // /// ******************************************************************************* // /// Back to Service SchedularCallback Function // /// When FileSearch is completed process flow return to Service1.SchedularCallback. // /// ------------------------------------------------------------------------------- //} // ************************************************************************ // Process all files in the directory passed in, recurse on any directories // that are found, and process the files they contain. // ------------------------------------------------------------------------ //public void ProcessDirectory(string targetDirectory, EtlTimer sync) /// NOT USED IN Version 3.0 //{ // /// // string[] fileEntries = Directory.GetFiles(targetDirectory); // foreach (string fileName in fileEntries) // { // ProcessFile(fileName, sync); // } // // Recurse into subdirectories of this directory. // string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory); // foreach (string subdirectory in subdirectoryEntries) // ProcessDirectory(subdirectory, sync); //} /// ***************************************************************************************** /// Version 3.0 (Feb17-17) /// General files process - Only NIB XML valid Files are processed here: /// (1) - Select files to process depending on file extension and/or file name. /// (2) - Route process to the corresponding file types import process using delegates. /// (3) - Unrecognized file types and Service reading errors are detected here. /// (4) - Errors are logged in service log and reported through web services. /// ----------------------------------------------------------------------------------------- public void ProcessFile(string path, EtlTimer sync) { ServiceResponse errMsg = new ServiceResponse(); errMsg.FileType = "2"; // NIB file type errMsg.FileName = Path.GetFileName(path); //fileName + extension; errMsg.Status = "Not Processed"; errMsg.NISOrderId = Path.GetFileNameWithoutExtension(path);; /// string extension = (Path.GetExtension(path)).ToString(); string fileName = Path.GetFileNameWithoutExtension(path); try { /// ********************************************************************************* /// Select files acceptable to be process, all other file types (extension) will not /// be processed (they stay in the newFiles folder) and an error message is generated /// to the WebServices. /// NIB (2) files process /// All NIB files have .xml and or sent extension. /// --------------------------------------------------------------------------------- string prefix = fileName; prefix = prefix .Replace("website-account-", "Acc").Replace("website-design-", "Dsn").Replace("website-order-", "Ord"); prefix = prefix.Substring(0, 3); /// /// Validate if this file was already processed May16-2017 /// int dupFile = wtf.getImportLog(serviceId, "NBI", fileName + extension); //if (((extension == ".xml") || (extension == ".sent")) && ((prefix == "Acc") || (prefix == "Dsn") || (prefix == "Ord"))) if (dupFile == 0 && (((extension == ".xml") || (extension == ".sent")) && ((prefix == "Acc") || (prefix == "Dsn") || (prefix == "Ord")))) { XmlDocument doc = new XmlDocument(); // Read / Load selected file content as xml doc.Load(path); /// Instanciate Xml methods delegate Del handler = null; // Declare a class instance xml: ImportProcedure_NBI.XmlFiles.ImportProcess xml = new ImportProcedure_NBI.XmlFiles.ImportProcess(); /// Declare an interface instance xmlFile: ImportProcedure_NBI.XmlFiles.IXmlFiles xmlfile = xml; // (ImportProcedure_NBI.XmlFiles.IXmlFiles)xml /// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /// Identify all xml files and route them to the corresponding import procedure /// Replace FileName with prefix's to simplify file type identification. /// ---------------------------------------------------------------------------- if (prefix == "Acc") { // NBI - Website-Accounts Files handler = xmlfile.ProcessWebsiteAccountFiles; } else if (prefix == "Dsn") { // NBI - Website-Designs Files handler = xmlfile.ProcessWebsiteDesignFiles; } else if (prefix == "Ord") { // NBI - Website-Order Files process handler = xmlfile.ProcessWebsiteOrderFiles; } /// =========== > bool ok = handler(doc, fileName, sync); // Process file and WebService icr.SaveProcessedFile(path, ok, sync, "NBI"); /// ===========> //ProcessXml(path, doc, fileName, handler, sync); /// < =========== } else { /// Unrecognized file type /// Initialize Error messages object basic information /// errMsg.Status = "Not Processed"; errMsg.NISOrderId = fileName; if (dupFile > 0) { errMsg.Message = "(NBI ProcessFile) File <" + fileName + extension + ">, duplicate file - already processed."; } else { errMsg.Message = "(NBI ProcessFile) File <" + fileName + extension + ">, unrecognized file type."; } wtf.writeSyncLog(1, Convert.ToInt16(ConfigurationManager.AppSettings["ServiceID"]), 1, sync.ServiceName, errMsg.Message); /// Duplicate file control May16-2017 /// if (dupFile == 0) { icr.SaveProcessedFile(path, false, sync, "STK"); } else { File.Delete(path); } /// < =========== } } catch (Exception fle) { int res = wtf.updImportControl(serviceId, 0); // set EtlTimer for this service to not Running (isRunning = false) errMsg.Message = "(NBI ProcessFile) Xml reading error - File in " + errMsg.FileName + ". " + fle; wtf.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, errMsg.Message); } }
protected async Task <ServiceResponse <T> > HandleApiOperationAsync <T>( Func <Task <ServiceResponse <T> > > action, [CallerLineNumber] int lineNo = 0, [CallerMemberName] string method = "") { var _logger = LogManager.GetLogger(typeof(BaseController)); _logger.Info($">>> ENTERS ({method}) >>> "); var serviceResponse = new ServiceResponse <T> { Code = HttpHelpers.GetStatusCodeValue(HttpStatusCode.OK), ShortDescription = "SUCCESS" }; try { if (!ModelState.IsValid) { throw new LMEGenericException("There were errors in your input, please correct them and try again.", HttpHelpers.GetStatusCodeValue(HttpStatusCode.BadRequest)); } var actionResponse = await action(); serviceResponse.Object = actionResponse.Object; serviceResponse.ShortDescription = actionResponse.ShortDescription ?? serviceResponse.ShortDescription; serviceResponse.Code = actionResponse.Code ?? serviceResponse.Code; } catch (LMEGenericException ex) { _logger.Warn($"L{lineNo} - {ex.ErrorCode}: {ex.Message}"); serviceResponse.ShortDescription = ex.Message; serviceResponse.Code = ex.ErrorCode ?? HttpHelpers.GetStatusCodeValue(HttpStatusCode.BadRequest); if (!ModelState.IsValid) { serviceResponse.ValidationErrors = ModelState.ToDictionary( m => { var tokens = m.Key.Split('.'); return(tokens.Length > 0 ? tokens[tokens.Length - 1] : tokens[0]); }, m => m.Value.Errors.Select(e => e.Exception?.Message ?? e.ErrorMessage) ); } } catch (DbUpdateException duex) when(duex.IsDatabaseFkDeleteException(out _databaseErrorMessage)) { _logger.Warn($"L{lineNo} - DFK001: {_databaseErrorMessage}"); serviceResponse.ShortDescription = "You cannot delete this record because it's currently in use."; serviceResponse.Code = "DFK001"; } catch (DbUpdateException duex) when(duex.IsUpdateConcurrencyException(out _databaseErrorMessage)) { _logger.Warn($"L{lineNo} - DCU001: {_databaseErrorMessage}"); serviceResponse.ShortDescription = "An error occured while updating your record"; serviceResponse.Code = "DCU001"; } catch (Exception ex) { _logger.Warn($"L{lineNo} - DBV001: {ex.Message}"); serviceResponse.ShortDescription = ex.Message; serviceResponse.Code = HttpHelpers.GetStatusCodeValue(HttpStatusCode.InternalServerError); _logger.Error(ex.Message, ex); } _logger.Info($"<<< EXITS ({method}) <<< "); return(serviceResponse); }
public ServiceResult AddLog(AffiliateLog access) { if (access == null) { return(ServiceResponse.Error("No data sent.")); } NetworkHelper network = new NetworkHelper(); access.ClientIp = network.GetClientIpAddress(this.Request); AffiliateManager affliateManager = new AffiliateManager(Globals.DBConnectionKey, this.GetAuthToken(this.Request)); access.DateCreated = DateTime.UtcNow; var logRes = affliateManager.InsertLog(access); if (CurrentUser == null) { CurrentUser = this.GetUser(this.GetAuthToken(this.Request)); } if (CurrentUser == null) { return(logRes); } UserManager um = new UserManager(Globals.DBConnectionKey, this.GetAuthToken(this.Request)); User referringUser = new User(); string type = access.NameType?.ToUpper(); switch (type) { case "USER": referringUser = um.Search(access.Name, false).FirstOrDefault(x => x.Name.EqualsIgnoreCase(access.Name) || x.UUID == access.Name); if (referringUser == null) { return(logRes); } var userRes = um.GetUser(CurrentUser.UUID, false); if (userRes.Code == 200) { var targetUser = (User)userRes.Result; if (string.IsNullOrWhiteSpace(access.ClientUserUUID)) { access.ClientUserUUID = CurrentUser.UUID; } access.ReferringUUID = referringUser.UUID; access.ReferringUUIDType = referringUser.UUIDType; affliateManager.UpdateLog(access); if (referringUser.UUID == CurrentUser.UUID) { return(logRes); } // if the user doesn't have a referring member set, then this user get it. if (string.IsNullOrWhiteSpace(targetUser.ReferringMember)) { targetUser.ReferringMember = referringUser.UUID; targetUser.ReferralDate = DateTime.UtcNow; um.Update(targetUser); } } break; case "ACCOUNT": //this is most likely out bound case "EVENT": //this is most likely out bound if (string.IsNullOrWhiteSpace(access.ClientUserUUID)) { access.ClientUserUUID = CurrentUser.UUID; } var usr = um.Get(CurrentUser.UUID); if (usr.Code == 200) { access.ReferringUUID = ((User)usr.Result).ReferringMember; // CurrentUser.ReferringMember; //whomever signed up this user (if any), gets the referral to the outbound link } affliateManager.UpdateLog(access); break; case "PROFILE": break; //default: // referringUser = um.Search(access.Name, false).FirstOrDefault(x => x.Name.EqualsIgnoreCase(access.Name)); // if (referringUser == null) // return logRes; // break; } return(logRes); }