public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) { System.IO.Directory.CreateDirectory(dataDir); } // Create a workbook object. Workbook workbook = new Workbook(); // Create a worksheet and get the first worksheet. Worksheet ExcelWorkSheet = workbook.Worksheets[0]; //Accessing the Validations collection of the worksheet ValidationCollection validations = workbook.Worksheets[0].Validations; //Creating a Validation object Validation validation = validations[validations.Add()]; //Setting the validation type to whole number validation.Type = ValidationType.WholeNumber; //Setting the operator for validation to Between validation.Operator = OperatorType.Between; //Setting the minimum value for the validation validation.Formula1 = "10"; //Setting the maximum value for the validation validation.Formula2 = "1000"; //Applying the validation to a range of cells from A1 to B2 using the //CellArea structure CellArea area; area.StartRow = 0; area.EndRow = 1; area.StartColumn = 0; area.EndColumn = 1; //Adding the cell area to Validation validation.AreaList.Add(area); // Save the workbook. workbook.Save(dataDir + "output.out.xls"); //ExEnd:1 }
public void Clear() { foreach (object obj in items) { UnsubscribeChanged(obj); } items.Clear(); ValidationCollection.Clear(); ChangeCollection(NotifyCollectionChangedAction.Reset); ChangeItem("Count"); }
public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) { System.IO.Directory.CreateDirectory(dataDir); } // Create a workbook object. Workbook workbook = new Workbook(); // Create a worksheet and get the first worksheet. Worksheet ExcelWorkSheet = workbook.Worksheets[0]; // Obtain the existing Validations collection. ValidationCollection validations = ExcelWorkSheet.Validations; // Create a validation object adding to the collection list. Validation validation = validations[validations.Add()]; // Set the validation type. validation.Type = ValidationType.Decimal; // Specify the operator. validation.Operator = OperatorType.Between; // Set the lower and upper limits. validation.Formula1 = Decimal.MinValue.ToString(); validation.Formula2 = Decimal.MaxValue.ToString(); // Set the error message. validation.ErrorMessage = "Please enter a valid integer or decimal number"; // Specify the validation area of cells. CellArea area; area.StartRow = 0; area.EndRow = 9; area.StartColumn = 0; area.EndColumn = 0; // Add the area. validation.AreaList.Add(area); // Save the workbook. workbook.Save(dataDir + "output.out.xls"); //ExEnd:1 }
public Provider(LyricsReloaded lyricsReloaded, string name, ushort quality, IDictionary <string, Variable> variables, FilterCollection postFilters, ValidationCollection validations, IDictionary <String, String> headers, LyricsLoader loader, RateLimit rateLimit = null) { this.lyricsReloaded = lyricsReloaded; this.name = name; this.quality = quality; this.variables = variables; this.postFilters = postFilters; this.validations = validations; this.headers = headers; this.loader = loader; this.rateLimit = rateLimit; }
public void UseValidation(IValidationCollection coll, string fieldName = null, string alternateLabel = null, string rowIndex = null) { VCollection = coll; if (VCollection == null) { VCollection = new ValidationCollection(Helper.GetFormName()); } string defName = InputModel.NgFormName + "__" + MemberName?.Replace(".", "_"); fieldName = (fieldName ?? defName) + (rowIndex == null ? "" : $"'+{rowIndex}+'"); VCollection.SetMember(ColumnId, fieldName, alternateLabel); ColumnModel.IsRequired = VCollection.HasRequired(); ColumnModel.ValidationMessages = GetCellErrors(VCollection); }
private IValidationCollection BuildCollectionFor(Type type) { var validationCollection = new ValidationCollection(); var properties = type.GetRuntimeProperties(); foreach (var propertyInfo in properties) { var attributes = propertyInfo.GetCustomAttributes(true).OfType<ValidationAttribute>().ToArray(); foreach (var validationAttribute in attributes) { validationCollection.Add( new ValidationInfo(propertyInfo, validationAttribute.CreateValidation(propertyInfo.PropertyType), validationAttribute.Groups)); } } return validationCollection; }
public MvcHtmlString TextAreaGroup(ValidationCollection <T> coll, int size, string alternateLabel, string placeHolder, object attrs, object inputAttr) { GroupModel.Label = alternateLabel == null?GetLabel(typeof(T).Name, MemberName) : alternateLabel; GroupModel.Size = size; GroupModel.Attributes = ToAttributeString(attrs); InputModel.PlaceHolder = placeHolder != null ? placeHolder : GroupModel.Label; InputModel.AttributeObject = inputAttr; InitializeValidations(coll, alternateLabel); GroupModel.InputControl = GetInputControl(ComponentNames.Textarea); return(GetView("Components/ControlGroup", GroupModel)); }
private IValidationCollection BuildCollectionFor(Type type) { var validationCollection = new ValidationCollection(); var properties = type.GetRuntimeProperties(); foreach (var propertyInfo in properties) { var attributes = propertyInfo.GetCustomAttributes(true).OfType <ValidationAttribute>().ToArray(); foreach (var validationAttribute in attributes) { validationCollection.Add( new ValidationInfo(propertyInfo, validationAttribute.CreateValidation(propertyInfo.PropertyType), validationAttribute.Groups)); } } return(validationCollection); }
protected override void OnMetadataProcess(ModelMetadata meta, string name, ViewDataDictionary viewData, ControllerContext context) { base.OnMetadataProcess(meta, name, viewData, context); if (meta.AdditionalValues.ContainsKey(AbstractValidationAttribute.KEY)) { ValidationCollection validations = (ValidationCollection)meta.AdditionalValues[AbstractValidationAttribute.KEY]; AbstractValidation required = validations.FirstOrDefault(v => v is PresenceValidation); if (required != null) { this.UncheckedValue = "false"; } } }
private ValidationResult GetResult(string testName, AbstractPluginManager pluginManager, string message, string reportingTest, ResolutionCallback callback = null) { ValidationResult result = ValidationCollection.GetOrCreate(SettingName + " - " + testName, pluginManager, reportingTest); result.Message = message; result.impact = ValidationResult.Level.Warning; result.Callbacks = new List <ResolutionCallback>(); if (callback != null) { result.AddCallback(callback); } else { AddDefaultFixCallback(result); } return(result); }
public void UseValidation(IValidationCollection coll, string fieldName = null, string alternateLabel = null) { VCollection = coll; if (VCollection == null) { VCollection = new ValidationCollection(Helper.GetFormName()); } VCollection.SetMember(ColumnId, fieldName ?? InputModel.FieldName, alternateLabel); GroupModel.IsRequired = VCollection.HasRequired(); if (GroupModel.IsRequired) { GroupModel.RequiredCondition = VCollection.GetRequiredCondition(); } GroupModel.ValidationMessages = VCollection.GetMessages(Helper); }
public static T getUserInput <T>(IHttpContext context, ValidationCollection validation) where T : class, IHasBasicIndexer { NameValueCollection data; dynamic target = (T)Activator.CreateInstance(typeof(T)); if (context.Request.HttpMethod == Grapevine.Shared.HttpMethod.GET) { data = context.Request.QueryString; } else { data = Parsers.parseURLEncoded(context.Request.Payload); } PropertyInfo[] properties = typeof(T).GetProperties(); var res = HttpUtility.ParseQueryString(context.Request.Payload); foreach (PropertyInfo property in properties) { if (validation.rows.ContainsKey(property.Name)) { foreach (validateDelegate del in validation.rows[property.Name]) { if (!del.Invoke(data[property.Name])) { return(null); } } Type currentType = property.PropertyType; if (data[property.Name] != null) { var converter = TypeDescriptor.GetConverter(currentType); var val = converter.ConvertFromString(data[property.Name]); property.SetValue(target, val, null); } } } return(target); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) { System.IO.Directory.CreateDirectory(dataDir); } // Create a workbook. Workbook workbook = new Workbook(); // Obtain the cells of the first worksheet. Cells cells = workbook.Worksheets[0].Cells; // Put a string value into A1 cell. cells["A1"].PutValue("Please enter Time b/w 09:00 and 11:30 'o Clock"); // Set the row height and column width for the cells. cells.SetRowHeight(0, 31); cells.SetColumnWidth(0, 35); // Get the validations collection. ValidationCollection validations = workbook.Worksheets[0].Validations; // Create Cell Area CellArea ca = new CellArea(); ca.StartRow = 0; ca.EndRow = 0; ca.StartColumn = 0; ca.EndColumn = 0; // Add a new validation. Validation validation = validations[validations.Add(ca)]; // Set the data validation type. validation.Type = ValidationType.Time; // Set the operator for the data validation. validation.Operator = OperatorType.Between; // Set the value or expression associated with the data validation. validation.Formula1 = "09:00"; // The value or expression associated with the second part of the data validation. validation.Formula2 = "11:30"; // Enable the error. validation.ShowError = true; // Set the validation alert style. validation.AlertStyle = ValidationAlertType.Information; // Set the title of the data-validation error dialog box. validation.ErrorTitle = "Time Error"; // Set the data validation error message. validation.ErrorMessage = "Enter a Valid Time"; // Set and enable the data validation input message. validation.InputMessage = "Time Validation Type"; validation.IgnoreBlank = true; validation.ShowInput = true; // Set a collection of CellArea which contains the data validation settings. CellArea cellArea; cellArea.StartRow = 0; cellArea.EndRow = 0; cellArea.StartColumn = 1; cellArea.EndColumn = 1; // Add the validation area. validation.AddArea(cellArea); // Save the Excel file. workbook.Save(dataDir + "output.out.xls"); // ExEnd:1 }
/// <summary> /// 初始化excel /// </summary> /// <param name="isFile">是否为文件模式(对应是否为ismport)</param> /// <param name="attachment"></param> /// <param name="template"></param> /// <param name="sheets"></param> /// <param name="configs"></param> /// <param name="selects"></param> /// <returns></returns> public Workbook InitExcel(bool isFile, Attachment attachment, Template template, List <TemplateSheet> sheets, List <TemplateConfig> configs, List <TemplateConfigSelect> selects) { ExcelEngine engine = new ExcelEngine(); Workbook wb = null; if (!isFile) { wb = new Workbook(); wb.Worksheets.Clear(); } else { var stream = FileUploadHelper.DownLoadFileStream(attachment.AttachmentPath, attachment.IsUseV1).ToStream(); stream.Seek(0, SeekOrigin.Begin); wb = new Workbook(stream); } #region init style StyleFlag styleFlag = new StyleFlag() { All = true, Borders = true }; CellsColor bcolor = wb.CreateCellsColor(); bcolor.ColorIndex = 36; CellsColor ccolor = wb.CreateCellsColor(); ccolor.ColorIndex = 36; CellsColor tcolor = wb.CreateCellsColor(); tcolor.ColorIndex = 36; Style style = wb.Styles[wb.Styles.Add()]; style.Font.Size = 18; style.Font.Name = "微软雅黑"; style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center; style.VerticalAlignment = Aspose.Cells.TextAlignmentType.Fill; style.ForegroundColor = System.Drawing.Color.White; style.Pattern = BackgroundType.Solid; style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; style.Borders[BorderType.TopBorder].Color = System.Drawing.Color.Black; style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;; style.Borders[BorderType.BottomBorder].Color = System.Drawing.Color.Black; style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;; style.Borders[BorderType.LeftBorder].Color = System.Drawing.Color.Black; style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; style.Borders[BorderType.RightBorder].Color = System.Drawing.Color.Black; style.VerticalAlignment = TextAlignmentType.Center; style.HorizontalAlignment = TextAlignmentType.Center; Style markStyle = wb.Styles[wb.Styles.Add()]; markStyle.Font.Size = 15; markStyle.Font.Name = "微软雅黑"; markStyle.IsTextWrapped = true; markStyle.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Right; markStyle.VerticalAlignment = Aspose.Cells.TextAlignmentType.Fill; markStyle.ForegroundColor = System.Drawing.Color.Yellow; markStyle.Pattern = BackgroundType.Solid; markStyle.Borders[BorderType.TopBorder].LineStyle = CellBorderType.None; markStyle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.None; markStyle.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.None; markStyle.Borders[BorderType.RightBorder].LineStyle = CellBorderType.None; markStyle.VerticalAlignment = TextAlignmentType.Center; markStyle.HorizontalAlignment = TextAlignmentType.Left; Style contentStyle = wb.Styles[wb.Styles.Add()]; //contentStyle.IsLocked = false; contentStyle.Font.Name = "Arial"; contentStyle.Font.Size = 10; contentStyle.Pattern = BackgroundType.Solid; //contentStyle.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; // contentStyle.Borders[BorderType.TopBorder].Color = System.Drawing.Color.FromArgb(155, 194, 230); contentStyle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;; contentStyle.Borders[BorderType.BottomBorder].Color = System.Drawing.Color.White; contentStyle.IsTextWrapped = true; contentStyle.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;; contentStyle.Borders[BorderType.LeftBorder].Color = bcolor.Color; contentStyle.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; contentStyle.Borders[BorderType.RightBorder].Color = bcolor.Color; contentStyle.VerticalAlignment = TextAlignmentType.Center; contentStyle.HorizontalAlignment = TextAlignmentType.Left; Style contentStyle1 = wb.Styles[wb.Styles.Add()]; //contentStyle1.IsLocked = false; contentStyle1.Font.Name = "Arial"; contentStyle1.Font.Size = 10; //221, 235, 247 contentStyle1.ForegroundColor = ccolor.Color; contentStyle1.Pattern = BackgroundType.Solid; //contentStyle1.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //contentStyle1.Borders[BorderType.TopBorder].Color = System.Drawing.Color.FromArgb(155, 194, 230); contentStyle1.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; contentStyle1.Borders[BorderType.BottomBorder].Color = bcolor.Color; contentStyle1.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;; contentStyle1.Borders[BorderType.LeftBorder].Color = bcolor.Color; contentStyle1.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; contentStyle1.Borders[BorderType.RightBorder].Color = bcolor.Color; contentStyle1.VerticalAlignment = TextAlignmentType.Center; contentStyle1.HorizontalAlignment = TextAlignmentType.Left; Style titleStyle = wb.Styles[wb.Styles.Add()]; //contentStyle.IsLocked = false; titleStyle.Font.Size = 12; titleStyle.Font.Name = "微软雅黑"; titleStyle.ForegroundColor = tcolor.Color; titleStyle.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Right; titleStyle.VerticalAlignment = Aspose.Cells.TextAlignmentType.Fill; titleStyle.Pattern = BackgroundType.Solid; titleStyle.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; titleStyle.Borders[BorderType.TopBorder].Color = System.Drawing.Color.Black; titleStyle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;; titleStyle.Borders[BorderType.BottomBorder].Color = System.Drawing.Color.Black; titleStyle.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;; titleStyle.Borders[BorderType.LeftBorder].Color = System.Drawing.Color.Black; titleStyle.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; titleStyle.Borders[BorderType.RightBorder].Color = System.Drawing.Color.Black; titleStyle.VerticalAlignment = TextAlignmentType.Center; titleStyle.HorizontalAlignment = TextAlignmentType.Center; #endregion foreach (var sheet in sheets) { int beforeCount = wb.Worksheets.Count; //重名异常,忽略 try { wb.Worksheets.Add(sheet.TemplateSheetName); } catch (Exception e) { int afterCount = wb.Worksheets.Count; if (afterCount > beforeCount) { wb.Worksheets.RemoveAt(wb.Worksheets.Count - 1); } } var itemConfigs = configs.Where(x => x.TemplateSheetID == sheet.ID).ToList(); //var configs = TemplateConfigOperator.Instance.GetList(sheet.TemplateID, sheet.ID); itemConfigs = itemConfigs.OrderBy(p => p.SortIndex).ToList(); int startIndex = sheet.ColumnNum - 1; if (!isFile) { Range r = wb.Worksheets[sheet.TemplateSheetName].Cells.CreateRange(0, startIndex, sheet.RowNum - 1, itemConfigs.Count); r.Merge(); r[0, 0].PutValue(sheet.TemplateSheetTitle); r.ColumnWidth = 13.88; r.RowHeight = 48.75; //r[0, 0].SetStyle(style); if (sheet.TemplateSheetRemark != null && sheet.TemplateSheetRemark != "") { Range rr = wb.Worksheets[sheet.TemplateSheetName].Cells.CreateRange(11, startIndex, 5, itemConfigs.Count); rr.Merge(); rr[0, 0].PutValue(sheet.TemplateSheetRemark); rr[0, 0].SetStyle(markStyle); } } if (itemConfigs.Count > 0) { Range dataRange = wb.Worksheets[sheet.TemplateSheetName].Cells.CreateRange(sheet.RowNum, sheet.ColumnNum - 1, 9, itemConfigs.Count); dataRange.Name = "DataName" + sheet.TemplateSheetName; } foreach (var config in itemConfigs) { Style cStyle = new Style(); #region 格式枚举 //Value Type Format String //0 General General //1 Decimal 0 //2 Decimal 0.00 //3 Decimal #,##0 //4 Decimal #,##0.00 //5 Currency $#,##0;$-#,##0 //6 Currency $#,##0;[Red]$-#,##0 //7 Currency $#,##0.00;$-#,##0.00 //8 Currency $#,##0.00;[Red]$-#,##0.00 //9 Percentage 0 % //10 Percentage 0.00 % //11 Scientific 0.00E+00 //12 Fraction # ?/? //13 Fraction # / //14 Date m/ d / yy //15 Date d-mmm - yy //16 Date d-mmm //17 Date mmm-yy //18 Time h:mm AM/ PM //19 Time h:mm: ss AM/ PM //20 Time h:mm //21 Time h:mm: ss //22 Time m/ d / yy h: mm //37 Currency #,##0;-#,##0 //38 Currency #,##0;[Red]-#,##0 //39 Currency #,##0.00;-#,##0.00 //40 Currency #,##0.00;[Red]-#,##0.00 //41 Accounting _ * #,##0_ ;_ * "_ ;_ @_ //42 Accounting _ $* #,##0_ ;_ $* "_ ;_ @_ //43 Accounting _ * #,##0.00_ ;_ * "??_ ;_ @_ //44 Accounting _ $* #,##0.00_ ;_ $* "??_ ;_ @_ //45 Time mm:ss //46 Time h :mm: ss //47 Time mm:ss.0 //48 Scientific ##0.0E+00 //49 Text @ #endregion // Obtain the existing Validations collection. ValidationCollection validations = wb.Worksheets[sheet.TemplateSheetName].Validations; // Create a validation object adding to the collection list. Validation validation = validations[validations.Add()]; CellArea area; switch (config.FieldType) { case "Text": cStyle.Number = 49; break; case "Number": cStyle.Number = 1; if (config.Digit != 0) { cStyle.Custom = "0.".PadRight(config.Digit + 2, '0'); } // Set the validation type. validation.Type = ValidationType.Decimal; // Specify the operator. validation.Operator = OperatorType.Between; // Set the lower and upper limits. validation.Formula1 = Decimal.MinValue.ToString(); validation.Formula2 = Decimal.MaxValue.ToString(); // Set the error message. validation.ErrorMessage = ""; // Specify the validation area of cells. area.StartRow = sheet.RowNum; area.EndRow = 1048575; area.StartColumn = startIndex; area.EndColumn = startIndex; // Add the area. validation.AreaList.Add(area); break; case "DateTiem": cStyle.Number = 15; cStyle.Custom = "yyyy-m-d"; // Set the data validation type. validation.Type = ValidationType.Date; // Set the operator for the data validation validation.Operator = OperatorType.Between; // Set the value or expression associated with the data validation. validation.Formula1 = "1970-1-1"; // The value or expression associated with the second part of the data validation. validation.Formula2 = "2099-12-31"; // Enable the error. validation.ShowError = true; // Set the validation alert style. validation.AlertStyle = ValidationAlertType.Stop; // Set the title of the data-validation error dialog box validation.ErrorTitle = "r"; // Set the data validation error message. validation.ErrorMessage = ""; // Set and enable the data validation input message. validation.InputMessage = ""; validation.IgnoreBlank = true; validation.ShowInput = true; // Set a collection of CellArea which contains the data validation settings. area.StartRow = sheet.RowNum; area.EndRow = 1048575; area.StartColumn = startIndex; area.EndColumn = startIndex; validation.AreaList.Add(area); break; } styleFlag = new StyleFlag() { NumberFormat = true, VerticalAlignment = true, HorizontalAlignment = true, FontSize = true, FontColor = true }; var colors = config.BGColor.Split(','); cStyle.ForegroundColor = System.Drawing.Color.FromArgb(int.Parse(colors[0]), int.Parse(colors[1]), int.Parse(colors[2])); cStyle.Pattern = BackgroundType.Solid; if (!isFile) { wb.Worksheets[sheet.TemplateSheetName].Cells.ApplyColumnStyle(startIndex, cStyle, styleFlag); wb.Worksheets[sheet.TemplateSheetName].Cells[0, 0].SetStyle(style); wb.Worksheets[sheet.TemplateSheetName].Cells[sheet.RowNum - 1, startIndex].PutValue(config.FieldName); wb.Worksheets[sheet.TemplateSheetName].Cells[sheet.RowNum - 1, startIndex].SetStyle(titleStyle); } if (config.BGColor != "255,255,255") { wb.Worksheets[sheet.TemplateSheetName].Cells[sheet.RowNum - 1, startIndex].SetStyle(cStyle); } var selectedValues = selects.FindAll(x => x.TemplateConfigID == config.ID);// TemplateConfigSelectOperator.Instance.GetList(sheet.TemplateID, sheet.ID, config.ID); if (selectedValues.Count > 0) { var hidSheet = wb.Worksheets["勿删除"]; if (hidSheet == null) { hidSheet = wb.Worksheets.Add("勿删除"); } hidSheet.IsVisible = false; Range range = hidSheet.Cells.CreateRange(50, itemConfigs.Count + 10 + startIndex, selectedValues.Count, 1); range.Name = "MyRange" + sheet.TemplateSheetName + startIndex; int i = 0; foreach (var item in selectedValues) { range[i, 0].PutValue(item.SelectedValue); i++; } validation = validations[validations.Add()]; validation.Type = Aspose.Cells.ValidationType.List; validation.Operator = OperatorType.None; validation.InCellDropDown = true; validation.Formula1 = "=MyRange" + sheet.TemplateSheetName + startIndex; validation.ShowError = true; validation.AlertStyle = ValidationAlertType.Stop; validation.ErrorTitle = "Error"; validation.ErrorMessage = ""; area.StartRow = sheet.RowNum; area.EndRow = 1048575; area.StartColumn = startIndex; area.EndColumn = startIndex; validation.AreaList.Add(area); } startIndex++; } if (!isFile) { wb.Worksheets[sheet.TemplateSheetName].AutoFilter.SetRange(sheet.RowNum - 1, sheet.ColumnNum - 1, itemConfigs.Count - 1); } } wb.FileName = template.TemplateName; if (wb.Worksheets.Count > 0 && wb.Worksheets[0].IsVisible) { wb.Worksheets.ActiveSheetIndex = 0; } return(wb); }
public static ModelField CreateModelFieldFromMeta(ModelMetadata propertyMetadata, Ext.Net.Model storeModel = null, ModelFieldAttribute modelAttr = null, ControllerContext controllerContext = null) { var modelField = new ModelField(); if (modelAttr == null) { modelAttr = propertyMetadata.AdditionalValues.ContainsKey(ModelFieldAttribute.KEY) ? (ModelFieldAttribute)propertyMetadata.AdditionalValues[ModelFieldAttribute.KEY] : null; } modelField.Name = propertyMetadata.PropertyName; if (Store.IsDate(propertyMetadata.ModelType)) { modelField.Type = ModelFieldType.Date; } else if (Store.IsInteger(propertyMetadata.ModelType)) { modelField.Type = ModelFieldType.Int; } else if (Store.IsFloat(propertyMetadata.ModelType)) { modelField.Type = ModelFieldType.Float; } else if (Store.IsBoolean(propertyMetadata.ModelType)) { modelField.Type = ModelFieldType.Boolean; } else if (propertyMetadata.ModelType == typeof(string)) { modelField.Type = ModelFieldType.String; } if (propertyMetadata.IsComplexType && modelAttr != null) { modelField.IsComplex = true; } if (modelAttr != null && storeModel != null) { modelAttr.CopyTo(modelField, storeModel); } if(storeModel != null) { storeModel.Fields.Add(modelField); } ValidationCollection validations = new ValidationCollection(); if (propertyMetadata.AdditionalValues.ContainsKey(AbstractValidationAttribute.KEY)) { validations = (ValidationCollection)propertyMetadata.AdditionalValues[AbstractValidationAttribute.KEY]; } foreach (ModelValidator v in propertyMetadata.GetValidators(controllerContext)) { var rule = v.GetClientValidationRules().FirstOrDefault(); if (rule != null) { switch (rule.ValidationType) { case "required": validations.Add(new PresenceValidation { Message = rule.ErrorMessage }); break; case "regex": if (rule.ValidationParameters.ContainsKey("pattern")) { validations.Add(new FormatValidation { Matcher = rule.ValidationParameters["pattern"].ToString(), Message = rule.ErrorMessage }); } break; case "length": int num; LengthValidation length = new LengthValidation(); length.Message = rule.ErrorMessage; if (rule.ValidationParameters.ContainsKey("max")) { if (int.TryParse(rule.ValidationParameters["max"].ToString(), out num)) { length.Max = num; } else { continue; } } if (rule.ValidationParameters.ContainsKey("min")) { if (int.TryParse(rule.ValidationParameters["min"].ToString(), out num)) { length.Min = num; } else { continue; } } validations.Add(length); break; } } } if (controllerContext != null) { foreach (ModelValidator v in propertyMetadata.GetValidators(controllerContext)) { var rule = v.GetClientValidationRules().FirstOrDefault(); if (rule != null) { switch (rule.ValidationType) { case "required": validations.Add(new PresenceValidation { Field = modelField.Name, Message = rule.ErrorMessage }); break; case "regex": if (rule.ValidationParameters.ContainsKey("pattern")) { validations.Add(new FormatValidation { Field = modelField.Name, Matcher = rule.ValidationParameters["pattern"].ToString(), Message = rule.ErrorMessage }); } break; case "length": var lengthVal = new LengthValidation(); if (rule.ValidationParameters.ContainsKey("max")) { lengthVal.Max = (int)Convert.ChangeType(rule.ValidationParameters["max"], typeof(int)); } if (rule.ValidationParameters.ContainsKey("min")) { lengthVal.Min = (int)Convert.ChangeType(rule.ValidationParameters["min"], typeof(int)); } lengthVal.Message = rule.ErrorMessage; validations.Add(lengthVal); break; } } } } if (validations.Count > 0) { if (storeModel != null) { storeModel.Validations.AddRange(validations); } else { modelField.Validations = validations; } } return modelField; }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) { System.IO.Directory.CreateDirectory(dataDir); } // Create a new workbook. Workbook workbook = new Workbook(); // Obtain the cells of the first worksheet. Cells cells = workbook.Worksheets[0].Cells; //Put a string value into A1 cell. cells["A1"].PutValue("Please enter a string not more than 5 chars"); // Set row height and column width for the cell. cells.SetRowHeight(0, 31); cells.SetColumnWidth(0, 35); // Get the validations collection. ValidationCollection validations = workbook.Worksheets[0].Validations; // Add a new validation. Validation validation = validations[validations.Add()]; // Set the data validation type. validation.Type = ValidationType.TextLength; // Set the operator for the data validation. validation.Operator = OperatorType.LessOrEqual; // Set the value or expression associated with the data validation. validation.Formula1 = "5"; // Enable the error. validation.ShowError = true; // Set the validation alert style. validation.AlertStyle = ValidationAlertType.Warning; // Set the title of the data-validation error dialog box. validation.ErrorTitle = "Text Length Error"; // Set the data validation error message. validation.ErrorMessage = " Enter a Valid String"; // Set and enable the data validation input message. validation.InputMessage = "TextLength Validation Type"; validation.IgnoreBlank = true; validation.ShowInput = true; // Set a collection of CellArea which contains the data validation settings. CellArea cellArea; cellArea.StartRow = 0; cellArea.EndRow = 0; cellArea.StartColumn = 1; cellArea.EndColumn = 1; // Add the validation area. validation.AreaList.Add(cellArea); // Save the Excel file. workbook.Save(dataDir + "output.xls"); }
/// <summary> /// Loads a configuration from any TextReader /// </summary> /// <param name="configReader">the reader</param> /// <exception cref="InvalidConfigurationException">if an error occurs during configuration loading</exception> public void loadProvider(TextReader configReader) { YamlStream yaml = new YamlStream(); try { yaml.Load(configReader); } catch (Exception e) { throw new InvalidConfigurationException(e.Message, e); } YamlNode node; IDictionary <YamlNode, YamlNode> rootNodes = ((YamlMappingNode)yaml.Documents[0].RootNode).Children; string loaderName; node = (rootNodes.ContainsKey(Node.LOADER) ? rootNodes[Node.LOADER] : null); if (node is YamlScalarNode) { loaderName = ((YamlScalarNode)node).Value.Trim().ToLower(); } else { loaderName = "static"; } if (!loaderFactories.ContainsKey(loaderName)) { throw new InvalidConfigurationException("Unknown provider type " + loaderName + ", skipping"); } LyricsLoaderFactory loaderFactory = loaderFactories[loaderName]; node = (rootNodes.ContainsKey(Node.NAME) ? rootNodes[Node.NAME] : null); if (!(node is YamlScalarNode)) { throw new InvalidConfigurationException("No provider name given!"); } string name = ((YamlScalarNode)node).Value.Trim(); ushort quality = 50; node = (rootNodes.ContainsKey(Node.QUALITY) ? rootNodes[Node.QUALITY] : null); if (node is YamlScalarNode) { try { quality = Convert.ToUInt16(((YamlScalarNode)node).Value.Trim()); } catch (FormatException e) { throw new InvalidConfigurationException("Invalid quality value given, only positive numbers >= 0 are allowed!", e); } } RateLimit rateLimit = null; node = (rootNodes.ContainsKey(Node.RATE_LIMIT) ? rootNodes[Node.RATE_LIMIT] : null); if (node is YamlScalarNode) { rateLimit = RateLimit.parse(((YamlScalarNode)node).Value.Trim()); } node = (rootNodes.ContainsKey(Node.VARIABLES) ? rootNodes[Node.VARIABLES] : null); Dictionary <string, Variable> variables = new Dictionary <string, Variable>(); if (node is YamlMappingNode) { foreach (KeyValuePair <YamlNode, YamlNode> preparationEntry in ((YamlMappingNode)node).Children) { node = preparationEntry.Key; if (node is YamlScalarNode) { string variableName = ((YamlScalarNode)node).Value.ToLower(); if (variables.ContainsKey(variableName)) { throw InvalidConfigurationException.fromFormat("{0}: Variable already defined!", variableName); } node = preparationEntry.Value; // variable value without filters if (node is YamlScalarNode) { string typeString = ((YamlScalarNode)node).Value.ToLower(); try { Variable.Type variableType = VARIABLE_TYPES[typeString]; variables.Add(variableName, new Variable(variableName, variableType)); } catch { throw InvalidConfigurationException.fromFormat("{0}: Unknown variable type {1}!", variableName, typeString); } } // value with filters expected else if (node is YamlMappingNode) { YamlMappingNode variableConfig = (YamlMappingNode)node; node = variableConfig.Children[Node.Variables.TYPE]; if (!(node is YamlScalarNode)) { throw InvalidConfigurationException.fromFormat("{0}: Invalid variable type!", variableName); } Variable.Type type; string typeString = ((YamlScalarNode)node).Value.ToLower(); try { type = VARIABLE_TYPES[typeString]; } catch { throw InvalidConfigurationException.fromFormat("{0}: Unknown variable type {1}!", variableName, typeString); } FilterCollection filterCollection; node = (variableConfig.Children.ContainsKey(Node.Variables.FILTERS) ? variableConfig.Children[Node.Variables.FILTERS] : null); // variable reference if (node is YamlScalarNode) { string referencedVar = ((YamlScalarNode)node).Value.ToLower(); try { filterCollection = variables[referencedVar].getFilters(); } catch { throw InvalidConfigurationException.fromFormat("{0}: Unknown variable {1} referenced!", variableName, referencedVar); } } // a list of filters else if (node is YamlSequenceNode) { filterCollection = FilterCollection.parseList((YamlSequenceNode)node, filters); } else { throw new InvalidConfigurationException("Invalid filter option specified!"); } variables.Add(variableName, new Variable(variableName, type, filterCollection)); } } else { throw new InvalidConfigurationException("Invalid configration, aborting the configuration."); } } } foreach (KeyValuePair <string, Variable.Type> entry in VARIABLE_TYPES) { if (!variables.ContainsKey(entry.Key)) { variables.Add(entry.Key, new Variable(entry.Key, entry.Value)); } } node = (rootNodes.ContainsKey(Node.POST_FILTERS) ? rootNodes[Node.POST_FILTERS] : null); FilterCollection postFilters; if (node is YamlSequenceNode) { postFilters = FilterCollection.parseList((YamlSequenceNode)node, filters); } else { postFilters = new FilterCollection(); } node = (rootNodes.ContainsKey(Node.VALIDATIONS) ? rootNodes[Node.VALIDATIONS] : null); ValidationCollection validations; if (node is YamlSequenceNode) { validations = ValidationCollection.parseList((YamlSequenceNode)node, validators); } else { validations = new ValidationCollection(); } IDictionary <String, String> headers = new Dictionary <String, String>(); node = (rootNodes.ContainsKey(Node.HEADERS) ? rootNodes[Node.HEADERS] : null); if (node is YamlMappingNode) { foreach (KeyValuePair <YamlNode, YamlNode> entry in (YamlMappingNode)node) { if (entry.Key is YamlScalarNode && entry.Value is YamlScalarNode) { headers.Add(((YamlScalarNode)entry.Key).Value.Trim(), ((YamlScalarNode)entry.Value).Value); } } } YamlMappingNode configNode; node = (rootNodes.ContainsKey(Node.CONFIG) ? rootNodes[Node.CONFIG] : null); if (node is YamlMappingNode) { configNode = (YamlMappingNode)node; } else { configNode = new YamlMappingNode(); } LyricsLoader loader = loaderFactory.newLoader(configNode); Provider provider = new Provider(lyricsReloaded, name, quality, variables, postFilters, validations, headers, loader, rateLimit); logger.info("Provider loaded: " + provider.getName()); lock (providerLock) { if (providers.ContainsKey(provider.getName())) { logger.info("The provider {0} does already exist and will be replaced.", provider.getName()); providers.Remove(provider.getName()); } providers.Add(provider.getName(), provider); } }
public static void LoadReportCaption(string username, string language_id, string template, string function_id) { SYS_tblReportCaptionBUS busReport = new SYS_tblReportCaptionBUS(); DataTable dt = busReport.LoadImportCaption(username, language_id, function_id, true); Workbook wb = new Workbook(Temp + string.Format(@"\{0}", template)); Worksheet ws = wb.Worksheets[0]; int index = 0; int count = wb.Worksheets.Count; if (dt != null && dt.Rows.Count > 0) { try { FindOptions opts = new FindOptions(); opts.LookInType = LookInType.Values; opts.LookAtType = LookAtType.EntireContent; for (int i = 0; i < dt.Rows.Count; i++) { Cell cell = ws.Cells.Find("$" + dt.Rows[i]["ControlID"].ToString() + "$", null, opts); if (cell != null) { int column = cell.Column; ws.Replace("$" + dt.Rows[i]["ControlID"].ToString() + "$", dt.Rows[i]["Caption"].ToString()); if (Convert.ToBoolean(dt.Rows[i]["IsList"]) && cell != null) { string tmp = ""; tmp = ws.Cells[cell.Row + 1, cell.Column].Value + ""; DataTable dt2 = busReport.LoadComboDynamicList(username, language_id, "", dt.Rows[i]["TableName"] + "", "Code"); index++; if (dt2 != null && dt2.Rows.Count > 0) { wb.Worksheets[index].Name = dt.Rows[i]["TableName"] + ""; Worksheet ws1 = wb.Worksheets[index]; ws1.Cells.ImportDataTable(dt2, true, 0, 0, true, false); Range range = ws1.Cells.CreateRange(1, 0, dt2.Rows.Count, 1); range.Name = tmp; for (int j = 0; j < dt2.Rows.Count; j++) { AsposeCellsStyle.Cells.BackgroundColor(ws1.Cells[0, j], Color.Yellow); AsposeCellsStyle.Cells.Font.Color(ws1.Cells[0, j], Color.Red); } ws1.AutoFitColumns(); } CellArea cellArea; cellArea.StartRow = 2; cellArea.EndRow = ws.Cells.MaxRow; cellArea.StartColumn = cell.Column; cellArea.EndColumn = cell.Column; ValidationCollection validations = ws.Validations; Validation validation = validations[validations.Add(cellArea)]; validation.Type = ValidationType.List; validation.Operator = OperatorType.None; validation.InCellDropDown = true; validation.Formula1 = "=" + tmp; validation.ShowError = false; validation.AreaList.Add(cellArea); } } if (Convert.ToBoolean(dt.Rows[i]["IsRequire"])) { AsposeCellsStyle.Cells.Font.Color(cell, Color.Red); } } SaveExportCustom(wb, "HellDemons"); } catch (Exception ex) { Logger.Error(ex); return; } } }
public static MvcHtmlString TextAreaGroup <T, TValue>(this HtmlHelper <T> helper, Expression <Func <T, TValue> > exp, ValidationCollection <T> coll = null, int size = 6, string alternateLabel = null, string placeHolder = null, object attrs = null, object inputAttr = null) { return(new NgElement <T, TValue>(helper, exp).TextAreaGroup(coll, size, alternateLabel, placeHolder, attrs, inputAttr)); }
protected override void OnMetadataProcess(ModelMetadata meta, string name, ViewDataDictionary viewData, ControllerContext context) { base.OnMetadataProcess(meta, name, viewData, context); if (meta.IsRequired) { this.AllowBlank = false; } if (this.EmptyText.IsEmpty() && meta.Watermark.IsNotEmpty()) { this.EmptyText = meta.Watermark; } string type = meta.DataTypeName; if (type.IsNotEmpty()) { switch (type) { case "Date": this.InputType = Ext.Net.InputType.Date; break; case "DateTime": this.InputType = Ext.Net.InputType.DateTime; break; case "EmailAddress": this.InputType = Ext.Net.InputType.Email; this.StandardVtype = ValidationType.Email; break; case "Password": this.InputType = Ext.Net.InputType.Password; break; case "Time": this.InputType = Ext.Net.InputType.Time; break; case "Url": this.InputType = Ext.Net.InputType.Url; this.StandardVtype = ValidationType.Url; break; } } if (meta.AdditionalValues.ContainsKey(AbstractValidationAttribute.KEY)) { ValidationCollection validations = (ValidationCollection)meta.AdditionalValues[AbstractValidationAttribute.KEY]; AbstractValidation required = validations.FirstOrDefault(v => v is PresenceValidation); if (required != null) { this.AllowBlank = false; if (required.Message.IsNotEmpty()) { this.BlankText = required.Message; } } AbstractValidation email = validations.FirstOrDefault(v => v is EmailValidation); if (email != null) { this.StandardVtype = ValidationType.Email; if (email.Message.IsNotEmpty()) { this.VtypeText = email.Message; } } LengthValidation length = validations.FirstOrDefault(v => v is LengthValidation) as LengthValidation; if (length != null) { if (length.Max != int.MaxValue) { this.MaxLength = length.Max; } if (length.Min != int.MinValue) { this.MinLength = length.Min; } if (length.Message.IsNotEmpty()) { this.MaxLengthText = length.Message; this.MinLengthText = length.Message; } } FormatValidation format = validations.FirstOrDefault(v => v is FormatValidation) as FormatValidation; if (format != null) { this.Regex = format.Matcher; if (format.Message.IsNotEmpty()) { this.RegexText = format.Message; } } } }
public static ModelField CreateModelFieldFromMeta(ModelMetadata propertyMetadata, Ext.Net.Model storeModel = null, ModelFieldAttribute modelAttr = null, ControllerContext controllerContext = null) { var modelField = new ModelField(); if (modelAttr == null) { modelAttr = propertyMetadata.AdditionalValues.ContainsKey(ModelFieldAttribute.KEY) ? (ModelFieldAttribute)propertyMetadata.AdditionalValues[ModelFieldAttribute.KEY] : null; } modelField.Name = propertyMetadata.PropertyName; if (Store.IsDate(propertyMetadata.ModelType)) { modelField.Type = ModelFieldType.Date; } else if (Store.IsInteger(propertyMetadata.ModelType)) { modelField.Type = ModelFieldType.Int; } else if (Store.IsFloat(propertyMetadata.ModelType)) { modelField.Type = ModelFieldType.Float; } else if (Store.IsBoolean(propertyMetadata.ModelType)) { modelField.Type = ModelFieldType.Boolean; } else if (propertyMetadata.ModelType == typeof(string)) { modelField.Type = ModelFieldType.String; } if (propertyMetadata.IsComplexType && modelAttr != null) { modelField.IsComplex = true; } if (modelAttr != null && storeModel != null) { modelAttr.CopyTo(modelField, storeModel); } if (storeModel != null) { storeModel.Fields.Add(modelField); } ValidationCollection validations = new ValidationCollection(); if (propertyMetadata.AdditionalValues.ContainsKey(AbstractValidationAttribute.KEY)) { validations = (ValidationCollection)propertyMetadata.AdditionalValues[AbstractValidationAttribute.KEY]; } foreach (ModelValidator v in propertyMetadata.GetValidators(controllerContext)) { var rule = v.GetClientValidationRules().FirstOrDefault(); if (rule != null) { switch (rule.ValidationType) { case "required": validations.Add(new PresenceValidation { Message = rule.ErrorMessage }); break; case "regex": if (rule.ValidationParameters.ContainsKey("pattern")) { validations.Add(new FormatValidation { Matcher = rule.ValidationParameters["pattern"].ToString(), Message = rule.ErrorMessage }); } break; case "length": int num; LengthValidation length = new LengthValidation(); length.Message = rule.ErrorMessage; if (rule.ValidationParameters.ContainsKey("max")) { if (int.TryParse(rule.ValidationParameters["max"].ToString(), out num)) { length.Max = num; } else { continue; } } if (rule.ValidationParameters.ContainsKey("min")) { if (int.TryParse(rule.ValidationParameters["min"].ToString(), out num)) { length.Min = num; } else { continue; } } validations.Add(length); break; } } } if (controllerContext != null) { foreach (ModelValidator v in propertyMetadata.GetValidators(controllerContext)) { var rule = v.GetClientValidationRules().FirstOrDefault(); if (rule != null) { switch (rule.ValidationType) { case "required": validations.Add(new PresenceValidation { Field = modelField.Name, Message = rule.ErrorMessage }); break; case "regex": if (rule.ValidationParameters.ContainsKey("pattern")) { validations.Add(new FormatValidation { Field = modelField.Name, Matcher = rule.ValidationParameters["pattern"].ToString(), Message = rule.ErrorMessage }); } break; case "length": var lengthVal = new LengthValidation(); if (rule.ValidationParameters.ContainsKey("max")) { lengthVal.Max = (int)Convert.ChangeType(rule.ValidationParameters["max"], typeof(int)); } if (rule.ValidationParameters.ContainsKey("min")) { lengthVal.Min = (int)Convert.ChangeType(rule.ValidationParameters["min"], typeof(int)); } lengthVal.Message = rule.ErrorMessage; validations.Add(lengthVal); break; } } } } if (validations.Count > 0) { if (storeModel != null) { storeModel.Validations.AddRange(validations); } else { modelField.Validations = validations; } } return(modelField); }
public static MvcHtmlString ControlGroup <T, TValue>(this HtmlHelper <T> helper, Expression <Func <T, TValue> > exp, ValidationCollection <T> coll = null, string textType = "text", int size = 6, string alternateLabel = null, string placeHolder = null, object attrs = null, object inputAttr = null, string classes = "", string value = "") { return(new NgElement <T, TValue>(helper, exp).ControlGroup(coll, size, textType, alternateLabel, placeHolder, attrs, inputAttr, classes, value)); }
public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) { System.IO.Directory.CreateDirectory(dataDir); } // Create a workbook object. Workbook workbook = new Workbook(); // Get the first worksheet. Worksheet worksheet1 = workbook.Worksheets[0]; // Add a new worksheet and access it. int i = workbook.Worksheets.Add(); Worksheet worksheet2 = workbook.Worksheets[i]; // Create a range in the second worksheet. Range range = worksheet2.Cells.CreateRange("E1", "E4"); // Name the range. range.Name = "MyRange"; // Fill different cells with data in the range. range[0, 0].PutValue("Blue"); range[1, 0].PutValue("Red"); range[2, 0].PutValue("Green"); range[3, 0].PutValue("Yellow"); // Get the validations collection. ValidationCollection validations = worksheet1.Validations; // Create a new validation to the validations list. Validation validation = validations[validations.Add()]; // Set the validation type. validation.Type = Aspose.Cells.ValidationType.List; // Set the operator. validation.Operator = OperatorType.None; // Set the in cell drop down. validation.InCellDropDown = true; // Set the formula1. validation.Formula1 = "=MyRange"; // Enable it to show error. validation.ShowError = true; // Set the alert type severity level. validation.AlertStyle = ValidationAlertType.Stop; // Set the error title. validation.ErrorTitle = "Error"; // Set the error message. validation.ErrorMessage = "Please select a color from the list"; // Specify the validation area. CellArea area; area.StartRow = 0; area.EndRow = 4; area.StartColumn = 0; area.EndColumn = 0; // Add the validation area. validation.AreaList.Add(area); // Save the Excel file. workbook.Save(dataDir + "output.out.xls"); //ExEnd:1 }