public OperationResult ValidateEmail() { var op = new OperationResult(); if (string.IsNullOrWhiteSpace(this.EmailAdress)) { op.Success = false; op.AddMessage("Email adress is null"); } if (op.Success) { var isValidFormat = true; // Code here that validates the format of the email // using Regular Expressions if (!isValidFormat) { op.Success = false; op.AddMessage("Email adress is in incorrect format"); } var isRealDomain = true; // Code here that confirms whether domain exists if (!isRealDomain) { op.Success = false; op.AddMessage("Email adress has invalid domain"); } } return(op); }
public OperationResult ValidateEmail() { OperationResult result = new OperationResult(); if (string.IsNullOrWhiteSpace(this.EmailAddress)) { result.Success = false; result.AddMessage("Email address is empty or null"); } if (result.Success) { var isValidFormat = true; // code here, with regexp if (!isValidFormat) { result.Success = false; result.AddMessage("Email address is in invalid format"); } } if (result.Success) { var isRealDomain = true; // code for confirming domain if (!isRealDomain) { result.Success = false; result.AddMessage("Email address does not include a valid domain"); } } return(result); }
public OperationResult ValidateEmail() { var operationResult = new OperationResult(); if (string.IsNullOrWhiteSpace(this.EmailAddress)) { operationResult.Success = false; operationResult.AddMessage("Email address is null"); } if (operationResult.Success == true) { var isValidFormat = true; //Code here validates the format using Regular Expressions if (!isValidFormat) { operationResult.Success = false; operationResult.AddMessage("Email address not in a valid format"); } var isRealDomain = true; //Code here confirms whether domain exists if (!isRealDomain) { operationResult.Success = false; operationResult.AddMessage("Email address does not include a valid domain"); } } return(operationResult); }
/// <summary> /// Calculates the percent of the step goal reached. /// </summary> public OperationResult <decimal> CalculatePercentOfGoalStepsOR(string goalSteps, string actualSteps) { var operationResult = new OperationResult <decimal>(0m, ""); if (string.IsNullOrWhiteSpace(goalSteps)) { operationResult.AddMessage("Goal steps must be entered"); return(operationResult); } if (string.IsNullOrWhiteSpace(actualSteps)) { operationResult.AddMessage("Actual steps must be entered"); return(operationResult); } decimal goalStepCount = 0; if (!decimal.TryParse(goalSteps, out goalStepCount)) { operationResult.AddMessage("Goal steps must be numeric"); return(operationResult); } decimal actualStepCount = 0; if (!decimal.TryParse(actualSteps, out actualStepCount)) { operationResult.AddMessage("Actual steps must be numeric"); return(operationResult); } operationResult.Value = CalculatePercentOfGoalSteps(goalStepCount, actualStepCount); return(operationResult); }
public OperationResult ValidateEmail() { OperationResult op = new OperationResult(); if (string.IsNullOrWhiteSpace(this.EmailAddress)) { op.Success = false; op.AddMessage("Email address is null"); } if (op.Success) { bool isValidFormat = true; // code to validate format of the email if (!isValidFormat) { op.AddMessage("Email address is not in a correct format"); } } if (op.Success) { bool isRealDomain = true; // code to validate domain of the email if (!isRealDomain) { op.AddMessage("Email address does not include a valid domain"); } } return(op); }
/// <summary> /// Validates the customer email address. /// </summary> /// <returns></returns> public OperationResult <bool> ValidateEmail() { var op = new OperationResult <bool>(); if (string.IsNullOrWhiteSpace(this.EmailAddress)) { op.Value = false; op.AddMessage("Email address is null"); } if (op.Value) { var isValidFormat = true; // Code here that validates the format of the email // using Regular Expressions. if (!isValidFormat) { op.Value = false; op.AddMessage("Email address is not in a correct format"); } } if (op.Value) { var isRealDomain = true; // Code here that confirms whether domain exists. if (!isRealDomain) { op.Value = false; op.AddMessage("Email address does not include a valid domain"); } } return(op); }
public OperationResult ValidateEmail() { var operationResult = new OperationResult(); if (string.IsNullOrWhiteSpace(this.Email)) { operationResult.Success = false; operationResult.AddMessage("Email address is null"); } if (operationResult.Success) { var validFormat = true; if (!validFormat) { operationResult.Success = false; operationResult.AddMessage("Email address is not in a correct format"); } } if (operationResult.Success) { var realDomain = true; if (!realDomain) { operationResult.Success = false; operationResult.AddMessage("Email address does not include a valid domain"); } } return(operationResult); }
/// <summary> /// Download file from server /// </summary> /// <param name="remoteFile"></param> /// <param name="localFile"></param> public OperationResult download(string remoteFile, string localFile) { var op = new OperationResult(); try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(Path.Combine(host, remoteFile)); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.EnableSsl = false; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Get the FTP Server's Response Stream */ ftpStream = ftpResponse.GetResponseStream(); /* Open a File Stream to Write the Downloaded File */ FileStream localFileStream = new FileStream(localFile, FileMode.Create); /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[bufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); /* Download the File by Writing the Buffered Data Until the Transfer is Complete */ try { while (bytesRead > 0) { localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); } } catch (WebException ex) { op.Success = false; op.AddMessage(ex.Message); } /* Resource Cleanup */ localFileStream.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; } catch (WebException ex) { op.Success = false; op.AddMessage(ex.Message); } return(op); }
/// <summary> /// To send an email as notification or report of the system status /// </summary> /// <param name="_msg"></param> /// <param name="_title"></param> /// <returns></returns> public static OperationResult SendEmail(string _msg, string _title) { var op = new OperationResult(); if (string.IsNullOrWhiteSpace(_msg)) { op.Success = false; op.AddMessage("Body must not be empty"); return(op); } if (string.IsNullOrWhiteSpace(_title)) { op.Success = false; op.AddMessage("Title must not be empty"); return(op); } try { MailMessage mailMessage = new MailMessage(); var to = ReCPeople(); foreach (var m in to) { mailMessage.To.Add(m); } mailMessage.Subject = _title + DateTime.Now.ToString("yyyyMMdd"); mailMessage.Body = _msg; mailMessage.From = new MailAddress("*****@*****.**", "DANUBE"); SmtpClient smtpMail = new SmtpClient(); smtpMail.Host = "Exchange.bindawood.com"; mailMessage.IsBodyHtml = true; smtpMail.Send(mailMessage); op.Success = true; } catch (Exception e) { op.Success = false; op.AddMessage(e.Message); } return(op); }
/// <summary> /// Move the File to Source Folder /// </summary> /// <param name="file"></param> /// <returns></returns> public virtual OperationResult moveToSrcFolder(FileInfo file) { if (File.Exists(Path.Combine(srcF, file.Name))) { File.Delete(file.FullName); op.Success = false; op.AddMessage("File must be existing"); return(op); } try { File.Move(file.FullName, Path.Combine(srcF, file.Name)); op.Success = true; } catch (Exception e) { op.Success = false; op.AddMessage(e.Message); } return(op); }
public void PrivilegeCreatePOST_Should_Redisplay_With_Errors_After_Fail_ServiceCall() { // Arrange var controller = GetMockRepositoryController(); var serviceMock = new Mock <IRolesService>(); var privilege = new Privilege() { PrivilegeName = "MyPrivilege", PrivilegeDescription = "MyPrivilege Description" }; var mockedResult = new OperationResult(); mockedResult.SetFail(); var errorMessage = "ErrorMessage"; mockedResult.AddMessage(errorMessage); serviceMock.Setup(sm => sm.AddPrivilege(privilege)).Returns(mockedResult); controller.RolesService = serviceMock.Object; // Act var result = controller.CreatePrivilege(privilege) as ViewResult; // Assert Assert.IsNotNull(result); Assert.IsTrue(result.ViewData.ModelState.Count > 0); Assert.AreEqual(errorMessage, result.ViewData.ModelState[""].Errors[0].ErrorMessage); }
public void CreateRole_POST_ShouldReturnError_On_FailCreateCall_ToService() { // Arrange var controller = GetMockRepositoryController(); var mockRoleService = new Mock <IRolesService>(); var role = new Role() { RoleName = "MyNewRole", RoleDescription = "MyNew RoleDescription" }; var operationResult = new OperationResult(); operationResult.SetFail(); operationResult.AddMessage("ErrorMessage"); mockRoleService.Setup(ms => ms.AddRole(role)).Returns(operationResult); controller.RolesService = mockRoleService.Object; // Act var result = controller.CreateRole(role) as ViewResult; // Assert Assert.IsNotNull(result); Assert.IsTrue(result.ViewData.ModelState.Count > 0); Assert.AreEqual(result.ViewData.ModelState[""].Errors[0].ErrorMessage, "ErrorMessage"); }
private async Task <OperationResult> DownloadAsync(Package latestOnlineVersion, string packageToDownload) { var operationResult = new OperationResult(); // Try to create the Updates subdirectory. If this fails: return. if (!await this.TryCreateUpdatesSubDirectoryAsync()) { operationResult.Result = false; return(operationResult); } // Delete all files from the Updates subdirectory. If this fails, just continue. this.TryCleanUpdatesSubDirectory(); try { string downloadLink = Path.Combine(UpdateInformation.AutomaticDownloadLink, Path.GetFileName(packageToDownload)); this.downloadClient = new WebClient(); LogClient.Info("Update check: downloading file '{0}'", downloadLink); await this.downloadClient.DownloadFileTaskAsync(new Uri(downloadLink), packageToDownload + ".part"); operationResult.Result = true; } catch (Exception ex) { operationResult.Result = false; operationResult.AddMessage(ex.Message); } return(operationResult); }
public override bool Execute() { var timer = new Stopwatch(); timer.Start(); Log.LogMessage("NRoles v" + _Metadata.Version); if (ShowTrace) { SetUpTraceListener(); } IOperationResult result; try { result = new RoleEngine().Execute( new RoleEngineParameters(AssemblyPath) { TreatWarningsAsErrors = TreatWarningsAsErrors, RunPEVerify = false, References = References.Split(';') }); LogMessages(result); } catch (Exception ex) { result = new OperationResult(); result.AddMessage(Error.InternalError()); LogMessages(result); Log.LogErrorFromException(ex); } timer.Stop(); Log.LogMessage("NRoles done, took {0}s", (timer.ElapsedMilliseconds / 1000f)); return result.Success; }
// Get new word from WordList Words based no letter count public string RetrieveWord(List <string> usedWords, int letterCount) { var wordList = WordList.Instance().WordAndDefinitions.Select(w => w.Word).ToArray(); var wordArray = wordList.Where(w => w.Length == letterCount). Except(usedWords). ToArray(); var word = string.Empty; if (wordArray == null) { var opResults = new OperationResult() { Success = false }; opResults.AddMessage("Ran out of words"); return(null); } if (wordArray.Length == 0) { var opResults = new OperationResult() { Success = false }; opResults.AddMessage("No words with the desired lettercount"); return(null); } return(wordArray[_random.Next(wordArray.Length)]);; }
public OperationResult _getReqSList(string rStatus) { OperationResult op = new OperationResult(); try { var db = new dnbmssqlEntities(); var reqQQ = db.reqlists.Where(s => s.sts.Equals(rStatus) && s.rtype.Equals("sku")); var reqCnt = reqQQ.Count(); if (reqCnt.Equals(0)) { op.Success = false; return(op); } foreach (var item in reqQQ) { var objreq = db.ViewRankingSKURequests.FirstOrDefault(s => s.reqid.Equals(item.reqid)); new CSV().CreateCSV(new string[] { "002", objreq.sid.Substring(6, 3), "SKU", objreq.sid.Substring(0, 6), objreq.ffrom.Replace("-", ""), objreq.tto.Replace("-", ""), objreq.reqid, item.reqid.Substring(19, Convert.ToInt32(objreq.reqid.Length - 19)), objreq.dreq.Replace("-", ""), DateTime.Now.ToString("HH:mm:ss").Replace(":", ""), "0", "0", "0", "0", "0", objreq.sku1 }); item.sts = "processing"; } db.SaveChanges(); db.Dispose(); op.Success = true; op.AddMessage(reqCnt + " sku has been created"); return(op); } catch (Exception ex) { op.Success = false; op.AddMessage(ex.Message.ToString()); return(op); } }
public async Task <OperationResult> AddMemberToProduct(string username, int productId, string userId = null) { var saveResult = new OperationResult(); // Get the user by its username // If the id is not null (found user with auto complete), use it var memberId = !string.IsNullOrEmpty(userId) ? userId : await this.Db.Users .Where(x => x.UserName == username) .Select(x => x.Id) .FirstOrDefaultAsync(); // If the user exists if (!string.IsNullOrEmpty(memberId)) { // Create a new product member var productMember = new ProductMember() { MembershipType = Model.Enums.ProductMembershipType.Member, ProductId = productId, MemberId = memberId }; var isAlreadyAssigned = await this.Db.ProductMembers .Where(x => x.MemberId == productMember.MemberId && x.ProductId == productMember.ProductId) .AnyAsync(); // Only if this user isn't assigned to the project if (!isAlreadyAssigned) { this.Db.ProductMembers.Add(productMember); await this.Db.SaveChangesAsync(); } else { saveResult.AddMessage("add-member", "The given user is already assigned to this project", OperationResultMessageType.Error); } } else { saveResult.AddMessage("add-member", "Could not find the given user", OperationResultMessageType.Error); } return(saveResult); }
public OperationResult <AudioMetaData> MetaDataForFile(string fileName, bool returnEvenIfInvalid = false) { var r = new OperationResult <AudioMetaData>(); var result = MetaDataForFileFromIdSharp(fileName); if (result.Messages?.Any() == true) { foreach (var m in result.Messages) { r.AddMessage(m); } } if (result.Errors?.Any() == true) { foreach (var e in result.Errors) { r.AddError(e); } } if (!result.IsSuccess) { result = MetaDataForFileFromATL(fileName); if (result.Messages?.Any() == true) { foreach (var m in result.Messages) { r.AddMessage(m); } } if (result.Errors?.Any() == true) { foreach (var e in result.Errors) { r.AddError(e); } } } if (!result.IsSuccess) { r.AddMessage($"Missing Data `[{DetermineMissingRequiredMetaData(result.Data)}]`"); } r.Data = result.Data; r.IsSuccess = result.IsSuccess; return(r); }
public OperationResult PlaceOrder(Customer customer, Order order, Payment payment, bool allowSplitOrders, bool emailReceipt) { Debug.Assert(customerRepository != null, "Missing customer respository instance"); Debug.Assert(orderRepository != null, "Missing order repository instance"); Debug.Assert(inventoryRepository != null, "Missing inventory repository instance"); Debug.Assert(emailLibrary != null, "Missing email library instance"); OperationResult operationResult = new OperationResult(); if (customer == null) { throw new ArgumentNullException("Customer instance is null"); } if (order == null) { throw new ArgumentNullException("Order instance is null"); } if (payment == null) { throw new ArgumentNullException("Payment instance is null"); } customerRepository.Add(customer); orderRepository.Add(order); inventoryRepository.OrderItems(order, allowSplitOrders); payment.ProcessPayment(payment); if (emailReceipt) { operationResult = customer.ValidateEmail(); if (operationResult.Success) { customerRepository.Update(); emailLibrary.SendEmail(customer.EmailAddress, "Here is your receipt"); } else { //Log messages if (operationResult.MessageList.Any()) { operationResult.AddMessage(operationResult.MessageList[0]); } } } return(operationResult); }
public OperationResult PlaceOrder(Customer customer, Order order, Payment payment, bool allowSplitOrders, bool emailReceipt) { //Assertions - only used when debugging the application Debug.Assert(_customerRepository != null, "Missing customer repository instance"); Debug.Assert(_orderRepository != null, "Missing order repository instance"); Debug.Assert(_inventoryRepository != null, "Missing inventory repository instance"); Debug.Assert(_emailLibrary != null, "Missing email library instance"); if (customer == null) { throw new ArgumentNullException(nameof(customer)); } if (order == null) { throw new ArgumentNullException(nameof(order)); } if (payment == null) { throw new ArgumentNullException(nameof(payment)); } var op = new OperationResult(); _customerRepository.Add(customer); _orderRepository.Add(order); _inventoryRepository.OrderItems(order, allowSplitOrders); payment.ProcessPayment(); if (emailReceipt) { var result = customer.ValidateEmail(); if (result.Success) { _customerRepository.Update(); _emailLibrary.SendEmail(customer.EmailAddress, "Here is your reciept"); } else { // log the messages if (result.MessageList.Any()) { op.AddMessage(result.MessageList[0]); } } } return(op); }
public OperationResult PlaceOrder(Customer customer, Order order, Payment payment, bool allowSplitOrders, bool getEmailReceipt) { Debug.Assert(customerRepo != null, "Missing customer repository instance"); Debug.Assert(orderRepo != null, "Missing order repository instance"); Debug.Assert(invRepo != null, "Missing inventory repository instance"); Debug.Assert(emailLibrary != null, "Missing email library instance"); if (customer == null) { throw new ArgumentNullException("Customer cannot be null"); } if (order == null) { throw new ArgumentNullException("Order cannot be null"); } if (payment == null) { throw new ArgumentNullException("Payment cannot be null"); } // bools are ok, since they cannot be null var op = new OperationResult(); // TODO the below method should be changed to return something so I can properly update the op object customerRepo.Add(customer); orderRepo.Add(order); invRepo.OrderItems(order, allowSplitOrders); payment.ProcessPayment(); if (getEmailReceipt) { var result = customer.ValidateEmail(); if (result.Success) { customerRepo.Update(); emailLibrary.SendEmail(customer.EmailAddress, "Here is your receipt"); } else { // op.Success = false; //nope, since by this point the order was actually placed // Log messages if (result.MessageList.Any()) { op.AddMessage(result.MessageList[0]); } } } return(op); }
private OperationResult DecodeZplPlaylist(string playlistPath, ref string playlistName, ref List <string> filePaths) { OperationResult op = new OperationResult(); try { playlistName = System.IO.Path.GetFileNameWithoutExtension(playlistPath); XDocument zplDocument = XDocument.Load(playlistPath); // Get the title of the playlist var titleElement = (from t in zplDocument.Element("smil").Element("head").Elements("title") select t).FirstOrDefault(); if (titleElement != null) { // If assigning the title which is fetched from the <title/> element fails, // the filename is used as playlist title. try { playlistName = titleElement.Value; } catch (Exception) { // Swallow } } // Get the songs var mediaElements = from t in zplDocument.Element("smil").Element("body").Element("seq").Elements("media") select t; if (mediaElements != null && mediaElements.Count() > 0) { foreach (XElement mediaElement in mediaElements) { string fullTrackPath = this.GenerateFullTrackPath(playlistPath, mediaElement.Attribute("src").Value); if (!string.IsNullOrEmpty(fullTrackPath)) { filePaths.Add(fullTrackPath); } } } op.Result = true; } catch (Exception ex) { op.AddMessage(ex.Message); op.Result = false; } return(op); }
public OperationResult ValidateExcelDocument(IFormFile file) { OperationResult result = new OperationResult(); if (file == null) { result.Success = false; result.AddMessage(ResponseMessages.NoFile); } if (result.Success) { if (!IsFileExcelDocument(file)) { result.Success = false; result.AddMessage(ResponseMessages.InvaliData); } } return(result); }
public IOperationResult CheckComposition(TypeDefinition composition) { var rolesAndSelfTypes = _extractor.RetrieveRolesSelfTypes(composition); var nonMatching = rolesAndSelfTypes.Where(rs => !Matches(rs.SelfType, composition)); var result = new OperationResult(); nonMatching.ForEach(rs => result.AddMessage( Error.SelfTypeConstraintNotSetToCompositionType(composition, rs.Role.Resolve(), rs.SelfType))); return result; }
//public bool ValidateEmail() //{ // var valid = true; // if (string.IsNullOrEmpty(this.Email)) // { // valid = false; // } // return valid; //} // TAKE TWO - returning more than one value, return deatiled messages // returning a message //public bool ValidateEmail(ref string message) //{ // var valid = true; // if (string.IsNullOrEmpty(this.Email)) // { // valid = false; // message = "Email address is null"; // } // return valid; //} // TAKE THREE - OUT keyword (better than ref as it doesn't have to initialized) //public bool ValidateEmail(out string message) //{ // var valid = true; // if (string.IsNullOrEmpty(this.Email)) // { // valid = false; // message = "Email address is null"; // } // return valid; //} // TAKE FOUR - out/ref are code smells. use Tuble instead //public Tuple<bool, string> ValidateEmail() //{ // Tuple<bool, string> result = Tuple.Create(true, ""); // if (string.IsNullOrEmpty(this.Email)) // { // result = Tuple.Create(false, "Email address is null"); // } // return result; //} // TAKE FIVE - returning OperationResult custom object public OperationResult ValidateEmail() { OperationResult op = new OperationResult(); if (string.IsNullOrEmpty(this.Email)) { op.AddMessage("Email address is null"); op.Success = false; } return(op); }
public OperationResult PlaceOrder(Customer customer, Order order, Payment payment, bool allowSplitOrders, bool emailReceipt) { // This program makes assertions that certain functions are running (as functions below) // These will throw a warning during debuging if an assertion isn't true Debug.Assert(customerRepository != null, "Missing customer repository instance N***A"); Debug.Assert(orderRepository != null, "Missing order repository instance"); Debug.Assert(inventoryRepository != null, "Missing inventory repository instance"); Debug.Assert(emailLibrary != null, "Missing email library instance"); if (customer == null) { throw new ArgumentNullException("Customer instance is null"); } if (order == null) { throw new ArgumentNullException("Order instance is null"); } if (payment == null) { throw new ArgumentNullException("Payment instance is null"); } var op = new OperationResult(); customerRepository.Add(customer); orderRepository.Add(order); inventoryRepository.OrderItems(order, allowSplitOrders); payment.ProcessPayment(); if (emailReceipt) { var result = customer.ValidateEmail(); if (result.Success) { customerRepository.Update(); emailLibrary.SendEmail(customer.EmailAddress, "Here is your receipt"); } else { // log the messages if (result.MessageList.Any()) { op.AddMessage(result.MessageList[0]); } } } return(op); }
/// <summary> /// Remove Request CSV file if existing /// </summary> /// <param name="_pth"></param> public OperationResult RemoveIfRequestIsExist(string[] _pth) { try { foreach (var item in _pth) { if (File.Exists(item)) { File.Delete(item); } } op.Success = true; return(op); } catch (Exception) { op.Success = false; op.AddMessage("Error removing a file"); return(op); } }
// option 1: Return a value -> bool // option 2: Return void and throw exceptions. Note that we're throwing ArgumenExceptions // despite the fact that this method does not receive arguments, this indicates // that exceptions are not really meant to handle validation, they are meant // to handle exceptional conditions and failure reporting. // option 3: Returning a boolean and receive a message parameter as ref. // option 4: Return a tuple. // option 5: Return a new object. This is better than the previous ones. public OperationResult ValidateEmail() { var operationResult = new OperationResult(); if (string.IsNullOrWhiteSpace(this.EmailAddress)) { operationResult.Success = false; operationResult.AddMessage("Email Address is null"); } if (operationResult.Success) { var isValidFormat = true; // code here that validates the format of the email // using a regular expression. if (!isValidFormat) { operationResult.Success = false; operationResult.AddMessage("Email address is not in a correct format"); } } if (operationResult.Success) { var isRealDomain = true; // code here that confirms whether the domain exists. if (!isRealDomain) { operationResult.Success = false; operationResult.AddMessage("Email address does not include a valid domain"); } } return(operationResult); }
/// <summary> /// [3] OperationResult를 사용하여 다중 값 반환하는 이메일 확인 메서드 /// </summary> /// <returns></returns> public OperationResult ValidateEmailWithObject() { var op = new OperationResult(); if (String.IsNullOrWhiteSpace(this.Email)) { op.Success = false; op.AddMessage("이메일이 NULL입니다."); } if (op.Success) { var isValidFormat = true; // 여기에 이메일에 대한 유효성 검사를 진행하는 코드 구현 // 정규표현식 사용하면 됨. if (!isValidFormat) { op.Success = false; op.AddMessage("이메일이 형식에 맞지 않습니다."); } } if (op.Success) { var isRealDomain = true; // 여기에 실제 사용 가능한 도메인인지 확인하는 코드가 들어옴... 예를 들어, naver.com, daum.net, live.com 식으로 도메인 제한을 두고자한다면... if (!isRealDomain) { op.Success = false; op.AddMessage("지정한 도메인에 해당하는 이메일이 아닙니다."); } } return(op); }
public OperationResult ValidateEmail() { var op = new OperationResult(); if (string.IsNullOrWhiteSpace(this.EmaiAddress)) { //throw new ArgumentException("Email address is null"); op.Success = false; op.AddMessage("Email address is null"); } if (op.Success) { var isValidFormat = true; // Code here that validates the format of the email // using Regular Expressions if (!isValidFormat) { op.Success = false; op.AddMessage("Email address is not in a corret format"); } } if (op.Success) { var isRealDomain = true; // Code here that confirms whether domain exists if (!isRealDomain) { op.Success = false; op.AddMessage("Email address does not include a valid domain"); } } return(op); }
public OperationResult ValidateEmail() { var op = new OperationResult(); if (string.IsNullOrWhiteSpace(EmailAddress)) { op.Success = false; op.AddMessage("Email address is null"); } if (op.Success) { var isValidFormat = true; //Code here that validates the format of the email using reg ex if (!isValidFormat) { op.Success = false; op.AddMessage("Email is not in the correct format"); } } if (op.Success) { var isRealDomain = true; //Code here that confirms whether domain exists if (!isRealDomain) { op.Success = false; op.AddMessage("Email address does not include a valid domain"); } } return(op); }
public OperationResult PlaceOrder(Customer customer, Order order, Payment payment, bool allowSplitOrders, bool emailReceipt) { if (customer == null) { throw new ArgumentException("Customer instance is null"); } if (order == null) { throw new ArgumentException("Order instance is null"); } if (payment == null) { throw new ArgumentException("Payment instance is null"); } var op = new OperationResult(); customerRepository.Add(customer); OrderRepository.Add(order); inventoryRepository.OrderItems(order, allowSplitOrders); payment.ProcessPayment(payment); if (emailReceipt) { string message = string.Empty; var result = customer.ValidateEmail(); if (result.Success) { customerRepository.Update(); emailLibrary.SendEmail(customer.Email, "Here is your receipt"); } else { //log message if (result.MessageList.Any()) { op.AddMessage(result.MessageList[0]); } } } return(op); }
/// <summary> /// Checks the assembly for errors and return the result of the operation. /// </summary> /// <returns>Result of the operation.</returns> public IOperationResult Verify() { var result = new OperationResult(); var peVerifyPath = _peVerifyPath; if (!File.Exists(peVerifyPath)) { result.AddMessage(Error.PEVerifyDoesntExist(peVerifyPath)); return result; } if (_assembly != null) { using (var assemblyFile = new TemporaryFile(Directory.GetCurrentDirectory())) { _assembly.Write(assemblyFile.FilePath); Verify(assemblyFile.FilePath, peVerifyPath, result); } } else { Verify(_assemblyPath, peVerifyPath, result); } return result; }
private void CheckRoleDoesntImplementInterfacesExplicitly(OperationResult result) { var hasOverrides = _roleType.Methods.Any(m => m.HasOverrides); if (hasOverrides) { // Note: overrides can also be used in other languages that don't have the concept of explicit interface implementations. // TODO: This message is too specific for C# result.AddMessage(Error.RoleHasExplicitInterfaceImplementation(_roleType)); } }
private void CheckRoleDoesntComposeItself(OperationResult result) { if (_roleType.RetrieveDirectRoles().Any(role => role.Resolve() == _roleType)) { result.AddMessage(Error.RoleComposesItself(_roleType)); } }
private void CheckRoleHasNoPlaceholders(OperationResult result) { var members = new List<IMemberDefinition>(); _roleType.Properties.ForEach(m => members.Add(m)); _roleType.Events.ForEach(m => members.Add(m)); _roleType.Methods.ForEach(m => members.Add(m)); members.Where(m => m.IsMarkedAsPlaceholder()). ForEach(m => result.AddMessage(Error.RoleHasPlaceholder(m))); }
private void CheckRoleHasNoPInvokeMethods(OperationResult result) { _roleType.Methods.Where(m => m.IsPInvokeImpl). ForEach(m => result.AddMessage(Error.RoleHasPInvokeMethod(m))); }
static int Main(string[] args) { var timer = new Stopwatch(); timer.Start(); bool trace = false; bool quiet = false; bool warningsAsErrors = false; string input = null; string output = null; string peVerifyPath = null; int peVerifyTimeout = 5; // default 5s bool showHelp = false; var options = new OptionSet { { "h|help", "show options.", h => showHelp = h != null }, { "q|quiet", "shhh.", q => quiet = q != null }, { "evilwarnings", "treats warnings as errors.", wae => warningsAsErrors = wae != null }, { "o|out=", "output to VALUE (default is to overwrite the input file).", o => output = o }, { "peverifypath=", "path to the PEVerify executable to use to verify the resulting assembly.", (string pvp) => peVerifyPath = pvp }, { "peverifytimeout=", "sets the timeout in seconds to wait for PEVerify to check the generated assembly.", (int pvt) => peVerifyTimeout = pvt }, { "trace", "prints trace information (trust me, you don't want to see this).", t => trace = t != null } }; List<string> unnamed; try { unnamed = options.Parse(args); } catch (OptionException e) { ShowError(e.Message); return -1; } if (!quiet) { Console.WriteLine("NRoles v" + _Metadata.Version); } if (showHelp) { ShowHelp(options); return 0; } if (trace) { SetUpTraceListener(); } if (unnamed.Count != 1) { var invalid = string.Join(", ", unnamed.ToArray()); if (invalid.Length > 0) invalid = " Invalid parameters: " + invalid; ShowError("Provide valid parameters and one input assembly." + invalid); return -1; } input = unnamed[0]; IOperationResult result; try { result = new RoleEngine().Execute( new RoleEngineParameters(input, output) { TreatWarningsAsErrors = warningsAsErrors, RunPEVerify = peVerifyPath != null, PEVerifyPath = peVerifyPath, PEVerifyTimeout = peVerifyTimeout }); } catch (Exception ex) { result = new OperationResult(); result.AddMessage(Error.InternalError()); if (trace) { Console.WriteLine("Failed!"); Console.WriteLine(); Console.WriteLine(ex.ToString()); Console.WriteLine(); if (ex.InnerException != null) { Console.WriteLine("INNER " + ex.InnerException.Message); } var hresult = Marshal.GetHRForException(ex); Console.WriteLine("HRESULT 0x{0:x}", hresult); } } timer.Stop(); result.Messages.ForEach(message => Console.WriteLine(message)); if (!quiet) { // TODO: print statistics? timing, number of roles, number of compositions, etc... <= these would be like info messages... Console.WriteLine("Done, took {0}s", (timer.ElapsedMilliseconds / 1000f)); } if (!result.Success) return -1; return 0; }