public void TryValidateModel_TestAgainstModelClassAttribute() { ClassAttributeTestWidget model = new ClassAttributeTestWidget(); Type modelType = model.GetType(); WFModelMetaData metadata = new WFModelMetaData(); WFModelMetaData metadataExpected = new WFModelMetaData(); bool actual; model.Email = "*****@*****.**"; model.MaxLengthName = "goodname"; model.RequiredName = "reqname"; //Required model.Sprockets = 6; //Good sprocket count model.Price = 0.99d; //Good price model.NoErrorMessage = "reqmsg"; //Required - no error message defined model.Password = "******"; model.ConfirmPassword = "******"; actual = WFUtilities.TryValidateModel(model, "", new WFObjectValueProvider(model, ""), metadata, new WFTypeRuleProvider(modelType)); //There should be one error from the model attribute Assert.AreEqual(metadata.Errors.Count, 1); //Properties are not collected when an error does not exist //The reason is because there is no page to collect them for Assert.AreEqual(metadata.Properties.Count, 0); Assert.AreEqual(actual, false); }
public void TryValidateModel_TestAgainstModelSuccess() { TestWidget model = new TestWidget(); Type modelType = model.GetType(); WFModelMetaData metadata = new WFModelMetaData(); WFModelMetaData metadataExpected = new WFModelMetaData(); bool actual; model.Email = "*****@*****.**"; model.MaxLengthName = "goodname"; model.RequiredName = "reqname"; //Required model.Sprockets = 6; //Good sprocket count model.Price = 0.99d; //Good price model.NoErrorMessage = "reqmsg"; //Required - no error message defined actual = WFUtilities.TryValidateModel(model, "", new WFObjectValueProvider(model, ""), metadata, new WFTypeRuleProvider(modelType)); //No Errors Assert.AreEqual(metadata.Errors.Count, 0); //Properties are not collected when an error does not exist //The reason is because there is no page to collect them for Assert.AreEqual(metadata.Properties.Count, 0); Assert.AreEqual(actual, true); }
public void TryValidateModel_TestAJAXLikeValidation() { TestWidget model = new TestWidget(); Type modelType = model.GetType(); List <string> errors = null; WFModelMetaData metadata = new WFModelMetaData(); WFModelMetaData metadataExpected = new WFModelMetaData(); bool actual; Dictionary <string, string> values = new Dictionary <string, string>(); values.Add("model_RequiredName", "reqname"); values.Add("model_MaxLengthName", "toolongofaname"); values.Add("model_Sprockets", "4"); //bad sprocket value values.Add("model_Email", "bademail"); //bad email values.Add("model_Price", "999"); //bad price // NoErrorMessage property is NOT added and should NOT be present actual = WFUtilities.TryValidateModel(model, "model_", new WFDictionaryValueProvider(values), metadata, new WFTypeRuleProvider(modelType)); errors = metadata.Errors; Assert.AreEqual(errors.Count, 4); Assert.AreEqual(errors[0], "Max length 10 characters"); Assert.AreEqual(errors[1], "Invalid number of sprockets."); Assert.AreEqual(errors[2], "Widget must have valid e-mail"); //Generated error message on custom annotation Assert.AreEqual(errors[3], "Invalid price"); Assert.AreEqual(actual, false); }
protected WFProcessor(uint port) { this.OutputFilesSpecified = true; this.OutputFiles = new WFFileList(); this.FileToProcess = string.Empty; this.TrackingId = Guid.NewGuid(); this.ParentTrackingId = this.TrackingId; this.WFManagerAdminProxy = null; this.ExportDirectory = string.Empty; this.IPAddress = string.Empty; this.Port = port; // try // { // this.SetProcessedObject = typeof(WFProcessingResult).GetMethod("SetProcessedObject").MakeGenericMethod(new [] { this.GetType() }); // } // catch (Exception ex) // { // throw new Exception(String.Format("No method named SetProcessedObject for type: {0}", this.GetType().FullName), ex); // } #if false string host = System.Net.Dns.GetHostName(); string ipaddress = string.Empty; if (WFUtilities.SetHostAndIPAddress(host, ref ipaddress)) { this.IPAddress = ipaddress; this.Port = port; } #endif }
public virtual Type GetTypeForControl() { Type modelType = null; if (String.IsNullOrEmpty(SourceTypeString)) { if (_sourceType == null && String.IsNullOrEmpty(XmlRuleSetName) && this.Page as IWFGetValidationRulesForPage == null) { throw new Exception("The SourceType and SourceTypeString properties are null/empty on one of the validator controls.\r\nPopulate either property.\r\nie: control.SourceType = typeof(Widget); OR in markup SourceTypeString=\"Assembly.Classes.Widget, Assembly\"\r\nThe page can also implement IWFGetValidationRulesForPage."); } else if (_sourceType == null && !String.IsNullOrEmpty(XmlRuleSetName)) { //Get the type from the XmlRuleSet SourceType = WFUtilities.GetRuleSetForName(XmlRuleSetName).ModelType; } else if (_sourceType == null && String.IsNullOrEmpty(XmlRuleSetName)) { SourceType = ((IWFGetValidationRulesForPage)this.Page).GetValidationClassType(); } } else { try { SourceType = Type.GetType(SourceTypeString, true, true); } catch (Exception ex) { throw new Exception("Couldn't resolve type " + SourceTypeString + ". You may need to specify the fully qualified assembly name."); } } return(SourceType); }
public void UrlDecodeDictionary_Tests() { Dictionary <string, string> request = WFUtilities.UrlDecodeDictionary(""); Assert.AreEqual(0, request.Count); request = WFUtilities.UrlDecodeDictionary("name=value"); Assert.AreEqual(1, request.Count); Assert.AreEqual("value", request["name"]); request = WFUtilities.UrlDecodeDictionary("name=value&name2=value2"); Assert.AreEqual(2, request.Count); Assert.AreEqual("value", request["name"]); Assert.AreEqual("value2", request["name2"]); request = WFUtilities.UrlDecodeDictionary("name=value&name=value2"); Assert.AreEqual(1, request.Count); Assert.AreEqual("value,value2", request["name"]); request = WFUtilities.UrlDecodeDictionary("&&name=value"); Assert.AreEqual(1, request.Count); Assert.AreEqual("value", request["name"]); request = WFUtilities.UrlDecodeDictionary("name=value&"); Assert.AreEqual(1, request.Count); Assert.AreEqual("value", request["name"]); request = WFUtilities.UrlDecodeDictionary("name&value"); Assert.AreEqual(2, request.Count); Assert.AreEqual("", request["name"]); Assert.AreEqual("", request["value"]); request = WFUtilities.UrlDecodeDictionary("name&name2=value2"); Assert.AreEqual(2, request.Count); Assert.AreEqual("", request["name"]); Assert.AreEqual("value2", request["name2"]); request = WFUtilities.UrlDecodeDictionary("name=value&name2"); Assert.AreEqual(2, request.Count); Assert.AreEqual("value", request["name"]); Assert.AreEqual("", request["name2"]); }
protected Processor(uint port) { this.WFManagerAdminProxy = null; this.IPAddress = string.Empty; this.Port = port; string host = System.Net.Dns.GetHostName(); string ipaddress = string.Empty; if (WFUtilities.SetHostAndIPAddress(host, ref ipaddress)) { this.IPAddress = ipaddress; this.Port = port; } #if false try { EndpointAddress ep = new EndpointAddress(new Uri(string.Format(@"http://{0}:{1}/WFManagerWCF/WFManagerWCF", this.IPAddress, this.Port))); // , EndpointIdentity.CreateDnsIdentity("localhost")); this.WFManagerAdminProxy = DuplexChannelFactory <Interfaces.Wcf.IWFManagerAdmin> .CreateChannel(this, new WSDualHttpBinding(), ep); WFLogger.NLogger.Trace("Discovery {0}", string.Format(@"http://{0}:{1}/WFManagerWCF/WFManagerWCF", this.IPAddress, this.Port)); this.WFManagerAdminProxy.Discovery(); WFLogger.NLogger.Trace("Discovery {0} Leaving", string.Format(@"http://{0}:{1}/WFManagerWCF/WFManagerWCF", this.IPAddress, this.Port)); } catch (Exception ex) { WFLogger.NLogger.ErrorException("ERROR: DuplexChannelFactory failed!", ex); } #endif }
public void RegisterXMLValidationConfiguration_TestLoadXML() { // // TODO: Add test logic here // WFUtilities.RegisterXMLValidationConfiguration(Environment.CurrentDirectory + "\\Validator.config"); Assert.AreEqual(1, WFUtilities.XmlRuleSets.Count()); Assert.AreEqual(4, WFUtilities.XmlRuleSets[0].Properties.Count); Assert.AreEqual(2, WFUtilities.XmlRuleSets[0].Properties[0].Validators.Count); }
public void RegisterXMLValidationConfiguration_TestClassLevelValidators() { WFUtilities.RegisterXMLValidationConfiguration(Environment.CurrentDirectory + "\\Validator3.config"); TestParticipantClass tpc = new TestParticipantClass(); tpc.Password = "******"; tpc.ConfirmPassword = "******"; WFModelMetaData metadata = new WFModelMetaData(); WFUtilities.TryValidateModel(tpc, "", new WFObjectValueProvider(tpc, ""), metadata, new WFXmlRuleSetRuleProvider("ClassLevelAttributes")); Assert.AreEqual("Password fields must match.", metadata.Errors[0]); }
public ActionResult EditCase(int id) { ApplicationUser manager = new ApplicationUser(WFEntities, this.Username); FlowInfo flowInfo = manager.GetFlowAndCase(id); var properties = manager.GetProperties(id); ViewBag.Properties = properties; var attachments = manager.GetAttachments(id); ViewBag.Attachments = attachments; ViewBag.FinalNotifyUsers = manager.GetFinalNotifyUsers(id); var flowType = WFEntities.WF_FlowTypes.FirstOrDefault(p => p.FlowTypeId == flowInfo.FlowTypeId); ViewBag.FlowType = flowType; ViewBag.HasCoverDuties = WFEntities.WF_FlowGroups.FirstOrDefault(p => p.FlowTypeId == flowInfo.FlowTypeId && p.StatusId > 0)?.HasCoverUsers; ViewBag.LeaveTypes = WFUtilities.GetLeaveType(RouteData.Values["lang"] as string); if (flowType.TemplateType.HasValue) { if (flowType.TemplateType.Value == 1) { ViewBag.Cities = WFEntities.Cities.Where(p => p.CountryCode == Country).AsNoTracking().ToArray(); } else if (flowType.TemplateType.Value == 7) { var prop = properties.PropertyInfo.FirstOrDefault(p => p.PropertyName.ToLower().Equals("brand") && p.StatusId < 0); if (prop != null) { var brand = properties.Values.FirstOrDefault(p => p.PropertyId == prop.FlowPropertyId)?.StringValue; var shopList = WFEntities.BLSShopView .Where(s => s.Brand.ToLower().Equals(brand.ToLower())) .Select(s => new { s.ShopCode, s.ShopName }) .ToDictionary(s => s.ShopCode, s => s.ShopName); ViewBag.ShopList = shopList; } } else if (flowType.TemplateType.Value == 2) { UserStaffInfo userInfo = WFUtilities.GetUserStaffInfo(this.Username); double balance = userInfo?.LeaveBalance ?? 0; double notstarted = manager.GetNotStartedBalance(Username); double unapproved = manager.GetUnApprovedBalance(Username); ViewBag.DisplayBalance = notstarted + balance; ViewBag.ValidBalance = balance > unapproved ? balance - unapproved : 0; } } return(PartialView(flowInfo)); }
public void ValidationMessageFor_LambdaTest() { TestParticipantClass tpc = GetTestParticipant(); string vmfOK = Html.ValidationMessageFor(m => m.FirstName); tpc.FirstName = ""; Html.MetaData = new WFModelMetaData(); //Reset metadata bool didValidate = WFUtilities.TryValidateModel(tpc, "", new WFObjectValueProvider(tpc, ""), Html.MetaData, new WFTypeRuleProvider(typeof(ProxyMessageFromValidator))); string vmfError = Html.ValidationMessageFor(m => m.FirstName); Assert.AreEqual("<span id = \"FirstName_validationMessage\" name = \"FirstName_validationMessage\" class = \"field-validation-valid\"></span>\r\n", vmfOK); Assert.AreEqual("<span id = \"FirstName_validationMessage\" name = \"FirstName_validationMessage\" class = \"field-validation-error\">The FirstName field is required.</span>\r\n", vmfError); Html.MetaData = new WFModelMetaData(); //Reset metadata }
public void TryValidateModel_TestProxyClassValidation() { FriendlyClass fc = new FriendlyClass(); fc.LastName = "onereallybiglongstringthatkeepsgoing"; // break validation List <string> errors = null; WFModelMetaData metadata = new WFModelMetaData(); bool didValidate = WFUtilities.TryValidateModel(fc, "", new WFObjectValueProvider(fc, ""), metadata, new WFTypeRuleProvider(typeof(FriendlyClass))); errors = metadata.Errors; Assert.AreEqual(false, didValidate); Assert.AreEqual(2, errors.Count); Assert.AreEqual("The FirstName field is required.", errors[0]); Assert.AreEqual("The field LastName must be a string with a maximum length of 10.", errors[1]); Assert.AreEqual(2, metadata.Properties.Count); }
public IEnumerable <ValidationAttribute> GetClassValidationAttributes() { try { if (RuleSet.ClassValidators != null && RuleSet.ClassValidators.Count > 0) { return(RuleSet.ClassValidators.Select(v => WFUtilities.GetValidatorInstanceForXmlDataAnnotationsValidator(v))); } else { return(new List <ValidationAttribute>() { }); } } catch (Exception ex) { throw new Exception("Error trying to get class-level validators. InnerException may have more detailed information.", ex); } }
protected override void RenderContents(HtmlTextWriter output) { if (String.IsNullOrEmpty(Path)) { output.Write(""); } else { if (_Model != null) { output.Write(WFUtilities.RenderControl(Path, _Model)); } else { output.Write(WFUtilities.RenderControl(Path)); } } }
public IEnumerable <ValidationAttribute> GetPropertyValidationAttributes(string propertyName) { try { XmlDataAnnotationsRuleSetProperty property = RuleSet.Properties.FirstOrDefault(p => p.PropertyName.ToLower() == propertyName.ToLower()); if (property != null) { return(property.Validators.Select(v => WFUtilities.GetValidatorInstanceForXmlDataAnnotationsValidator(v))); } else { return(new List <ValidationAttribute>() { }); } } catch (Exception ex) { throw new Exception("Error trying to get validators for " + propertyName + ". InnerException may have more detailed information.", ex); } }
public void TryValidateModel_ErrorMessageTests() { string resourceErrorMessage = Resources.FirstName_ErrorMessage_Test1; TestParticipantClass tpc = new TestParticipantClass(); WFModelMetaData metadata = new WFModelMetaData(); WFUtilities.TryValidateModel(tpc, "", new WFObjectValueProvider(tpc, ""), metadata, new WFTypeRuleProvider(typeof(ProxyMessageFromValidator))); Assert.AreEqual("The FirstName field is required.", metadata.Errors[0]); metadata = new WFModelMetaData(); WFUtilities.TryValidateModel(tpc, "", new WFObjectValueProvider(tpc, ""), metadata, new WFTypeRuleProvider(typeof(ProxyMessageFromConstant))); Assert.AreEqual("This is a constant error.", metadata.Errors[0]); metadata = new WFModelMetaData(); WFUtilities.TryValidateModel(tpc, "", new WFObjectValueProvider(tpc, ""), metadata, new WFTypeRuleProvider(typeof(ProxyMessageFromResource))); Assert.AreEqual("This value from resource.", metadata.Errors[0]); metadata = new WFModelMetaData(); }
public void TryValidateModel_TestAgainstModel() { TestWidget model = new TestWidget(); Type modelType = model.GetType(); List <string> errors = null; List <string> errorsExpected = new List <string>(); WFModelMetaData metadata = new WFModelMetaData(); WFModelMetaData metadataExpected = new WFModelMetaData(); bool expected = false; bool actual; model.Email = "bademail"; model.MaxLengthName = "toolongofaname"; model.RequiredName = ""; //Required model.Sprockets = 4; //Invalid sprocket count model.Price = 999; //Invalid price model.NoErrorMessage = ""; //Required - no error message defined actual = WFUtilities.TryValidateModel(model, "", new WFObjectValueProvider(model, ""), metadata, new WFTypeRuleProvider(modelType)); errors = metadata.Errors; Assert.AreEqual(errors.Count, 6); //Generated error messages on standard annotations Assert.AreEqual(errors[0], "Widget name required"); Assert.AreEqual(errors[1], "Max length 10 characters"); Assert.AreEqual(errors[2], "Invalid number of sprockets."); Assert.AreEqual(errors[3], "Widget must have valid e-mail"); //Generated error message on custom annotation Assert.AreEqual(errors[4], "Invalid price"); //Auto-generated error message Assert.AreEqual(errors[5], "The NoErrorMessage field is required."); Assert.AreEqual(metadata.Properties.Count, 6); Assert.AreEqual(metadata.Properties[0].PropertyName, "RequiredName"); Assert.AreEqual(metadata.Properties[1].PropertyName, "MaxLengthName"); Assert.AreEqual(metadata.Properties[2].PropertyName, "Sprockets"); Assert.AreEqual(metadata.Properties[3].PropertyName, "Email"); Assert.AreEqual(metadata.Properties[4].PropertyName, "Price"); Assert.AreEqual(metadata.Properties[5].PropertyName, "NoErrorMessage"); Assert.AreEqual(actual, false); }
public async Task <ActionResult> ChangePassword(string Password, string NewPassword, string ConfirmPassword) { if (User.Identity.Name == "Admin") { return(this.ShowErrorInModal("Admin cannot change password")); } if (NewPassword == ConfirmPassword) { LoginApiClient login = new LoginApiClient(); UserStaffInfo userInfo = WFUtilities.GetUserStaffInfo(this.Username); RequestResult <BoolResult> res = await login.ChangeUserPasswordAsync(User.Identity.Name, Password, NewPassword, userInfo.Country); if (!string.IsNullOrEmpty(res.ReturnValue.ret_msg)) { return(this.ShowErrorInModal(res.ReturnValue.ret_msg)); } return(this.ShowSuccessModal(StringResource.PASSWORD_CHANGE)); } return(this.ShowErrorInModal(StringResource.PASSWORD_INCONSISTENT)); }
public ActionResult FillFormValue(int flowtypeid) { ViewBag.Country = Country; UserStaffInfo userInfo = WFUtilities.GetUserStaffInfo(this.Username); ViewBag.CurrentDep = userInfo?.DepartmentName; WF_FlowTypes flowType = WFEntities.WF_FlowTypes.FirstOrDefault(p => p.FlowTypeId == flowtypeid && p.StatusId > 0); ViewBag.FlowType = flowType; if (flowType?.TemplateType.HasValue == true) { if (flowType.TemplateType.Value == (int)FlowTemplateType.DynamicTemplate) { var props = WFEntities.WF_FlowGroups.AsNoTracking() .Include("WF_FlowPropertys") .FirstOrDefault(p => p.FlowTypeId == flowtypeid && p.StatusId > 0)?.WF_FlowPropertys.ToArray(); return(PartialView("FillDynamicFormValue", props)); } if (flowType.TemplateType.Value == (int)FlowTemplateType.StoreApprovalTemplate) { ViewBag.Cities = WFEntities.Cities.Where(p => p.CountryCode == Country).AsNoTracking().ToArray(); } else if (flowType.TemplateType.Value == (int)FlowTemplateType.LeaveTemplate) { ApplicationUser manager = new ApplicationUser(WFEntities, this.Username); double balance = userInfo?.LeaveBalance ?? 0; double notstarted = manager.GetNotStartedBalance(Username); double unapproved = manager.GetUnApprovedBalance(Username); ViewBag.NotStartedBalance = notstarted; ViewBag.APIReturnBalance = balance; ViewBag.DisplayBalance = notstarted + balance; ViewBag.ValidBalance = balance > unapproved ? balance - unapproved : 0; ViewBag.LeaveTypes = WFUtilities.GetLeaveType(RouteData.Values["lang"] as string); } } ViewBag.StaffNo = this.Username; ViewBag.HasCoverDuties = WFEntities.WF_FlowGroups.FirstOrDefault(p => p.FlowTypeId == flowtypeid && p.StatusId > 0)?.HasCoverUsers; return(PartialView("FillFormValue", WFEntities.WF_FlowGroups.AsNoTracking().Include("WF_FlowPropertys").FirstOrDefault(p => p.FlowTypeId == flowtypeid && p.StatusId > 0))); }
public void TextBoxFor_LambdaTest() { TestParticipantClass tpc = GetTestParticipant(); string lambdaStr = Html.TextBoxFor(p => p.FirstName); Assert.AreEqual("<input name = \"FirstName\" id = \"FirstName\" type = \"text\" value = \"Michael\" />", lambdaStr); lambdaStr = Html.TextBoxFor(p => p.FirstName, new { Class = "clsTxt" }); Assert.AreEqual("<input name = \"FirstName\" id = \"FirstName\" type = \"text\" value = \"Michael\" class = \"clsTxt\" />", lambdaStr); //With an error tpc.FirstName = ""; Html.MetaData = new WFModelMetaData(); //Reset metadata bool didValidate = WFUtilities.TryValidateModel(tpc, "", new WFObjectValueProvider(tpc, ""), Html.MetaData, new WFTypeRuleProvider(typeof(ProxyMessageFromValidator))); string lambdaError = Html.TextBoxFor(p => p.FirstName); Assert.AreEqual("<input name = \"FirstName\" id = \"FirstName\" type = \"text\" value = \"\" class = \"input-validation-error\" />", lambdaError); Html.MetaData = new WFModelMetaData(); //Reset metadata tpc.FirstName = "&Michael"; lambdaStr = Html.TextBoxFor(p => p.FirstName, new { Class = "clsTxt" }); Assert.AreEqual("<input name = \"FirstName\" id = \"FirstName\" type = \"text\" value = \"&Michael\" class = \"clsTxt\" />", lambdaStr); }
public async Task <ActionResult> ChangePassword(string UserId, string Password, string NewPassword, string ConfirmPassword) { if (User.Identity.Name == "Admin") { ModelState.AddModelError("", (string)"Admin cannot change password"); return(View("ChangePassword", (object)UserId)); } if (NewPassword == ConfirmPassword) { LoginApiClient login = new LoginApiClient(); UserStaffInfo userInfo = WFUtilities.GetUserStaffInfo(UserId); RequestResult <BoolResult> res = await login.ChangeUserPasswordAsync(UserId, Password, NewPassword, userInfo.Country); if (!string.IsNullOrEmpty(res.ReturnValue.ret_msg)) { ModelState.AddModelError("", res.ReturnValue.ret_msg); return(View("ChangePassword", (object)UserId)); } return(RedirectToAction("LogOn")); } ModelState.AddModelError("", StringResource.PASSWORD_INCONSISTENT); return(View("ChangePassword", (object)UserId)); }
public WFXmlRuleSetRuleProvider(string ruleSetName) { RuleSet = WFUtilities.GetRuleSetForName(ruleSetName); ModelDisplayName = RuleSet.ModelDisplayName; }
public virtual PropertyInfo GetTargetProperty() { return(WFUtilities.GetTargetProperty(_propertyName, SourceType)); }
public override WFState Run() { WFState retval = new WFState() { Value = "Success" }; OpenMcdf.CompoundFile cf = null; try { cf = new CompoundFile(this.FileToProcess); bool attachfound = false; int attachinc = 0; do { CFStorage cfstorage = this.GetStorage(cf.RootStorage, MakeAttachStorageName(attachinc)); if (cfstorage != null) { // check if attachment is embedded message - if so do not process if (this.GetStorage(cfstorage, nameOfEmbeddedMessageStream) == null) { string filename = string.Format("attachment{0}", attachinc); // first get filename CFStream cfstream = this.GetStream(cfstorage, MakeSubStorageStreamName(0x3001, 0x001F)); if (cfstream != null) { filename = System.Text.UnicodeEncoding.Unicode.GetString(cfstream.GetData()); } // second get filename cfstream = this.GetStream(cfstorage, MakeSubStorageStreamName(0x3701, 0x0102)); if (cfstream != null) { string filedir = string.Format("{0}\\{1}", this.ExportDirectory, WFUtilities.GetNextDirectoryNumber(this.ExportDirectory)); if (!Directory.Exists(filedir)) { Directory.CreateDirectory(filedir); } if (Directory.Exists(filedir)) { using (var bw = new BinaryWriter(File.OpenWrite(string.Format("{0}\\{1}", filedir, filename)))) { bw.Write(cfstream.GetData()); this.OutputFiles.Add(string.Format("{0}\\{1}", filedir, filename), "Success"); } } } } attachfound = true; } else { attachfound = false; } attachinc++; } while(attachfound); } catch (Exception) { retval.Value = "Fail"; } finally { if (cf != null) { cf.Close(); } } return(retval); }
public void RegisterXMLValidationConfiguration_TestXMLErrorMessage() { WFUtilities.RegisterXMLValidationConfiguration(Environment.CurrentDirectory + "\\Validator2.config"); string resourceErrorMessage = Resources.FirstName_ErrorMessage_Test1; TestParticipantClass tpc = new TestParticipantClass(); WFModelMetaData metadata = new WFModelMetaData(); //============================= WEB FORMS SERVER CONTROL VALIDATION ================================= Page p = new Page(); p.Controls.Add(new TextBox() { ID = "FirstName" }); p.Controls.Add(new DataAnnotationValidatorControl() { PropertyName = "FirstName", ControlToValidate = "FirstName", XmlRuleSetName = "MessageFromValidator", ErrorMessage = "This message from control itself." }); p.Validators.Add(p.Controls[1] as IValidator); (p.Controls[1] as BaseValidator).Validate(); Assert.AreEqual("This message from control itself.", (p.Controls[1] as DataAnnotationValidatorControl).ErrorMessage); p = new Page(); p.Controls.Add(new TextBox() { ID = "FirstName" }); p.Controls.Add(new DataAnnotationValidatorControl() { PropertyName = "FirstName", ControlToValidate = "FirstName", XmlRuleSetName = "MessageFromXML", }); p.Validators.Add(p.Controls[1] as IValidator); (p.Controls[1] as BaseValidator).Validate(); Assert.AreEqual("The First Name field cannot be empty.", (p.Controls[1] as DataAnnotationValidatorControl).ErrorMessage); p = new Page(); p.Controls.Add(new TextBox() { ID = "FirstName" }); p.Controls.Add(new DataAnnotationValidatorControl() { PropertyName = "FirstName", ControlToValidate = "FirstName", XmlRuleSetName = "MessageFromResource", }); p.Validators.Add(p.Controls[1] as IValidator); (p.Controls[1] as BaseValidator).Validate(); Assert.AreEqual("This value from resource.", (p.Controls[1] as DataAnnotationValidatorControl).ErrorMessage); //====================== TryValidateModel ============================== WFUtilities.TryValidateModel(tpc, "", new WFObjectValueProvider(tpc, ""), metadata, new WFXmlRuleSetRuleProvider("MessageFromValidator")); Assert.AreEqual("The FirstName field is required.", metadata.Errors[0]); metadata = new WFModelMetaData(); WFUtilities.TryValidateModel(tpc, "", new WFObjectValueProvider(tpc, ""), metadata, new WFXmlRuleSetRuleProvider("MessageFromXML")); Assert.AreEqual("The First Name field cannot be empty.", metadata.Errors[0]); metadata = new WFModelMetaData(); WFUtilities.TryValidateModel(tpc, "", new WFObjectValueProvider(tpc, ""), metadata, new WFXmlRuleSetRuleProvider("MessageFromResource")); Assert.AreEqual("This value from resource.", metadata.Errors[0]); metadata = new WFModelMetaData(); }
protected void Application_Start(object sender, EventArgs e) { WFUtilities.RegisterXMLValidationConfiguration(Server.MapPath("\\") + "RegisterRules.xml"); }
public DisplayAttribute(Type resourceManagerProvider, string resourceKey) : base(WFUtilities.GetResourceValueFromTypeName(resourceManagerProvider, resourceKey)) { }
public override void Process(PdfFileParserData data) { data.WFState.Value = WFState.WFStateFail; Dictionary <String, byte[]> files = new Dictionary <String, byte[]>(); PdfReader reader = new PdfReader(data.DocumentToProcess); PdfReaderContentParser parser = new PdfReaderContentParser(reader); MyImageRenderListener listener = new MyImageRenderListener(); for (int i = 1; i <= reader.NumberOfPages; i++) { parser.ProcessContent(i, listener); } for (int i = 0; i < listener.Images.Count; ++i) { string filedir = string.Format("{0}\\{1}", Path.GetDirectoryName(data.DocumentToProcess), WFUtilities.GetNextDirectoryNumber(Path.GetDirectoryName(data.DocumentToProcess))); if (!Directory.Exists(filedir)) { Directory.CreateDirectory(filedir); } if (Directory.Exists(filedir)) { using (FileStream fs = new FileStream(string.Format("{0}\\{1}", filedir, listener.ImageNames[i]), FileMode.Create, FileAccess.Write)) { fs.Write(listener.Images[i], 0, listener.Images[i].Length); } data.OutputDocuments.Add(string.Format("{0}\\{1}", filedir, listener.ImageNames[i])); } } data.WFState.Value = KRSrcWorkflow.WFState.WFStateSuccess; }
private void HandleMessage(Message rdomail, string exportdir) { if (this.ProcessedMsgs.Contains(rdomail.Node)) { return; } this.ProcessedMsgs.Add(rdomail.Node); string msgdir = exportdir; if (this.SaveAsTypes != SaveAsType.None || this.SaveAttachments == true) { msgdir = msgdir + @"\" + rdomail.Node.ToString(); } if (!Directory.Exists(msgdir)) { Directory.CreateDirectory(msgdir); } if (Directory.Exists(msgdir)) { if ((this.SaveAsTypes & SaveAsType.Xml) == SaveAsType.Xml) { this.OutputFiles.Add(rdomail.Write(this.Pst2MsgCompatible ? exportdir + @"\XML" : msgdir, Message.SaveAsMessageType.Xml, true), "Xml"); } if ((this.SaveAsTypes & SaveAsType.Eml) == SaveAsType.Eml) { this.OutputFiles.Add(rdomail.Write(msgdir, Message.SaveAsMessageType.Eml, true)); } if ((this.SaveAsTypes & SaveAsType.Msg) == SaveAsType.Msg) { this.OutputFiles.Add(rdomail.Write(this.Pst2MsgCompatible ? exportdir + @"\MSG" : msgdir, Message.SaveAsMessageType.Msg, true), "Msg"); } if ((this.SaveAsTypes & SaveAsType.Html) == SaveAsType.Html) { this.OutputFiles.Add(rdomail.Write(msgdir, Message.SaveAsMessageType.Html, true), "Html"); } if (rdomail.HasBody && ((this.SaveAsTypes & SaveAsType.Text) == SaveAsType.Text)) { this.OutputFiles.Add(rdomail.Write(msgdir, Message.SaveAsMessageType.Text, true), "Text"); } if (rdomail.HasRtfBody && ((this.SaveAsTypes & SaveAsType.Rtf) == SaveAsType.Rtf)) { this.OutputFiles.Add(rdomail.Write(msgdir, Message.SaveAsMessageType.Rtf, true)); } foreach (pstsdk.definition.pst.message.IAttachment rdoattachment in rdomail.Attachments) { if (rdoattachment.IsMessage) { Message attachmsg = null; try { attachmsg = (Message)rdoattachment.OpenAsMessage(); attachmsg.Pst = rdomail.Pst; } catch (Exception ex) { WFLogger.NLogger.ErrorException(string.Format("PSTFile={0} NodeID={1}", this.PSTFile, this.FileToProcess), ex); } finally { if (attachmsg != null) { if (this.SaveEmbeddedMsgs == true && attachmsg.Node == Convert.ToUInt32(this.FileToProcess)) { SaveAsType origsaveastype = this.SaveAsTypes; this.SaveAsTypes = SaveAsType.Msg | SaveAsType.Xml | SaveAsType.Html; HandleMessage(attachmsg, exportdir); this.SaveAsTypes = origsaveastype; } else { this.OutputFiles.Add(attachmsg.Node.Value.ToString(), "EmbeddedMsg"); } } } } else if (this.SaveAttachments) { string filedir = string.Format("{0}\\{1}", msgdir, WFUtilities.GetNextDirectoryNumber(msgdir)); if (!Directory.Exists(filedir)) { Directory.CreateDirectory(filedir); } if (Directory.Exists(filedir)) { string filename = filedir + @"\" + rdoattachment.Filename; using (var bw = new BinaryWriter(File.OpenWrite(filename))) { bw.Write(rdoattachment.Bytes); this.OutputFiles.Add(filename, "Attachment"); } } } rdoattachment.Dispose(); } } }
/// <summary> /// /// </summary> /// <param name="country"></param> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <param name="fromTime">am/pm</param> /// <param name="toTime">am/pm</param> /// <returns></returns> public double GetTotalHoursWithoutHoliday(string country, string fromDate, string toDate, string fromTime, string toTime) { DateTime from, to; bool isDate_Form = DateTime.TryParse(fromDate, out from); bool isDate_To = DateTime.TryParse(toDate, out to); if (isDate_Form && isDate_To) { var hoursOfHalfDay = 4; UserHolidayInfo[] holidaysInfo = null; if (!String.IsNullOrEmpty(country)) { holidaysInfo = WFUtilities.GetHolidays(country, from.ToString("yyyyMMdd"), to.ToString("yyyyMMdd")); } var interval = to - from; var totalHours = (interval.TotalDays + 1) * hoursOfHalfDay * 2; string f = from.ToString("yyyyMMdd"); string t = to.ToString("yyyyMMdd"); if (fromTime.EqualsIgnoreCaseAndBlank("pm")) { totalHours -= hoursOfHalfDay; f += "2"; } else { f += "1"; } if (toTime.EqualsIgnoreCaseAndBlank("am")) { totalHours -= hoursOfHalfDay; t += "1"; } else { t += "2"; } int nf = int.Parse(f); int nt = int.Parse(t); if (holidaysInfo != null) { foreach (var info in holidaysInfo) { if (String.IsNullOrEmpty(info.Time)) { continue; } var date = DateTime.ParseExact(info.Date, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture); List <int> holidayList = new List <int>(); if (info.Time.EqualsIgnoreCaseAndBlank("all")) { string h1 = info.Date + "1"; string h2 = info.Date + "2"; holidayList.Add(int.Parse(h1)); holidayList.Add(int.Parse(h2)); } else if (info.Time.EqualsIgnoreCaseAndBlank("am")) { string h = info.Date + "1"; holidayList.Add(int.Parse(h)); } else if (info.Time.EqualsIgnoreCaseAndBlank("pm")) { string h = info.Date + "2"; holidayList.Add(int.Parse(h)); } foreach (var i in holidayList) { if (i >= nf && i <= nt) { totalHours -= 4; } } } } return(totalHours); } else { return(-1); } }