public void Serialize_any_class_to_a_set_of_attributes() { var schemaHelper = new SchemaHelper(); string schema = schemaHelper.Serialize<MyClassSerializeToSchemaAttributes>(true); Assert.AreEqual( "<Attribute Name=\"StringProperty\"/><Attribute Name=\"BoolProperty\" Choice=\"True,False\"/><Attribute Name=\"EnumProperty\" Choice=\"{" + typeof(Enum).FullName + "}\"/><Attribute Name=\"IntProperty\"/>", schema); }
public void Create_Application() { var helper = new SchemaHelper(); DictionaryNode node=helper.CreateElement(ModelElement.Application); var dictionaryNode = new DictionaryNode("Element"); dictionaryNode.SetAttribute("Name", ModelElement.Application.ToString()); Assert.AreEqual(dictionaryNode.ToXml(), node.ToXml()); }
public void Create_Class() { var helper = new SchemaHelper(); DictionaryNode node=helper.CreateElement(ModelElement.Class); var dictionaryNode = new DictionaryNode("Element"); dictionaryNode.SetAttribute("Name", ModelElement.Application.ToString()); var childNode = dictionaryNode.AddChildNode("Element"); childNode.SetAttribute("Name", ModelElement.BOModel.ToString()); childNode.AddChildNode("Element").SetAttribute("Name", ModelElement.Class.ToString()); Assert.AreEqual(dictionaryNode.ToXml(), node.ToXml()); }
public void Attributes_can_be_modified_before_creation() { var schemaHelper = new SchemaHelper(); schemaHelper.AttibuteCreating += (sender, args) => { args.Handled = true; args.Attribute = args.Attribute.Replace("Attribute", "ChangeAttribute"); }; string schema = schemaHelper.Serialize<MyClassSerializeToSchemaAttributes>(true); Assert.AreEqual( "<ChangeAttribute Name=\"StringProperty\"/><ChangeAttribute Name=\"BoolProperty\" Choice=\"True,False\"/><ChangeAttribute Name=\"EnumProperty\" Choice=\"{" + typeof(Enum).FullName + "}\"/><ChangeAttribute Name=\"IntProperty\"/>", schema); }
public override Schema GetSchema() { var schemaHelper = new SchemaHelper(); schemaHelper.AttibuteCreating += (sender, args) => modifyAttributes(args); string CommonTypeInfos = @"<Element Name=""" + ModelArtifactStateNodeWrapper.NodeNameAttribute + @"""> <Element Name=""" + GetElementStateGroupNodeName() + @"""> <Element Name=""" + GetElementStateNodeName() + @""" KeyAttribute=""ID"" Multiple=""True""> " + schemaHelper.Serialize<IStateRule>(true) + @" " + schemaHelper.Serialize<IArtifactStateRule>(true) + @" " + GetMoreSchema() + @" </Element> </Element> </Element>"; var schema = new Schema(schemaHelper.Inject(CommonTypeInfos, ModelElement.Application)); return schema; }
public override Schema GetSchema() { var schemaHelper = new SchemaHelper(); string CommonTypeInfos = @"<Element Name=""Application""> <Element Name=""BOModel"" > <Element Name=""Class"" > <Element Name=""" + GetElementStateActionName() + @"""> <Element Name=""Item"" KeyAttribute=""" + STR_Name + @""" DisplayAttribute=""" + STR_Name + @""" Multiple=""True""> " +GetMoreSchema() + @" " +schemaHelper.Serialize<IStateRule>(true) + @" </Element> </Element> </Element> </Element> </Element>"; return new Schema(new DictionaryXmlReader().ReadFromString(CommonTypeInfos)); }
static ColumnType[] IntToColumnTypes(int[] dtypes) { ColumnType[] kinds = null; if (dtypes != null) { kinds = new ColumnType[dtypes.Length]; for (int i = 0; i < kinds.Length; ++i) { if (dtypes[i] < 0) { kinds[i] = null; } else { var kind = (DataKind)dtypes[i]; var ctype = SchemaHelper.DataKind2ColumnType(kind); kinds[i] = ctype; } } } return(kinds); }
public DataViewRowCursor[] GetRowCursorSet(IEnumerable <DataViewSchema.Column> columnsNeeded, int n, Random rand = null) { n = DataViewUtils.GetThreadCount(n); if (n <= 1) { return new DataViewRowCursor[] { GetRowCursor(columnsNeeded, rand) } } ; else { //var cols = SchemaHelper.ColumnsNeeded(columnsNeeded, Schema, _args.columns); var cols = SchemaHelper.ColumnsNeeded(columnsNeeded, Source.Schema); var cursors = Source.GetRowCursorSet(cols, n, rand); for (int i = 0; i < cursors.Length; ++i) { cursors[i] = new AddRandomCursor(this, cursors[i]); } return(cursors); } }
public int AddColumn <DT>(string name, DT[] values) { var kind = SchemaHelper.GetColumnType <DT>(); switch (kind.RawKind()) { case DataKind.Boolean: return(AddColumn(name, values as bool[])); case DataKind.Int32: return(AddColumn(name, values as int[])); case DataKind.Int64: return(AddColumn(name, values as long[])); case DataKind.UInt32: return(AddColumn(name, values as uint[])); case DataKind.Single: return(AddColumn(name, values as float[])); case DataKind.Double: return(AddColumn(name, values as double[])); case DataKind.String: { if (values as string[] != null) { return(AddColumn(name, values as string[])); } if (values as DvText[] != null) { return(AddColumn(name, values as DvText[])); } if (values as ReadOnlyMemory <char>[] != null) { return(AddColumn(name, values as ReadOnlyMemory <char>[])); } throw Contracts.ExceptNotImpl($"Unable to add a column of type {typeof(DT)}."); } default: throw Contracts.ExceptNotImpl($"Unable to add a column of type {typeof(DT)}."); } }
public void GenerateUserProfileSchema() { if (ProfileList != null && ProfileList.Count > 0) { List <ListItem> itemList = new List <ListItem>(); int i = 1; foreach (TestUserProfile userProfile in ProfileList) { itemList.Add(new ListItem() { Position = i++, Item = SchemaHelper.GeneratePersonSchema(userProfile) }); } UserProfileSchema = new ItemList() { ItemListElement = itemList }.ToString(); } }
private void ValidateInputs(out int indexLabel, out int indexTime, out DataViewType typeLabel, out DataViewType typeTime) { indexLabel = SchemaHelper.GetColumnIndex(Source.Schema, _args.columns[0].Source); typeLabel = Source.Schema[indexLabel].Type; if (typeLabel.IsVector()) { if (typeLabel.AsVector().DimCount() != 1 || typeLabel.AsVector().GetDim(0) != 1) { throw Host.ExceptNotImpl("Not implemented yet for multiple dimensions."); } } if (typeLabel.RawKind() != DataKind.Single) { throw Host.ExceptNotImpl("InputColumn must be R4."); } indexTime = SchemaHelper.GetColumnIndex(Source.Schema, _args.timeColumn); typeTime = Source.Schema[indexTime].Type; if (typeTime.RawKind() != DataKind.Single) { throw Host.ExceptNotImpl("Time columne must be R4."); } }
/// <summary> /// Extracts outputs of a transform is not specified. /// </summary> /// <param name="view">transform</param> /// <param name="outputs">requested outputs or null to get them all</param> /// <param name="hidden">include hidden variables</param> public static void GuessOutputs(IDataView view, ref string[] outputs, bool hidden = false) { if (outputs == null) { var sch = view.Schema; outputs = Enumerable.Range(0, sch.ColumnCount) .Where(c => hidden || !sch.IsHidden(c)) .Select(c => sch.GetColumnName(c)).ToArray(); } else { var sch = view.Schema; int index; foreach (var name in outputs) { if (!sch.TryGetColumnIndex(name, out index)) { throw Contracts.Except($"Unable to find column '{name}' in\n{SchemaHelper.ToString(sch)}."); } } } }
protected List <ValidationResult> GetAnnotationValidationResults(ExecuteCommand <T> executeCommand) { // Assert(executeCommand.GetType() == typeof(InsertCommand<T>) || executeCommand.GetType() == typeof(UpdateCommand<T>)); List <ValidationResult> validationResults = new List <ValidationResult>(); XElement entitySchema = executeCommand.EntitySchema; foreach (KeyValuePair <string, object> pair in executeCommand.PropertyValues) { string propertyName = pair.Key; object propertyValue = pair.Value; XElement propertySchema = SchemaHelper.GetPropertySchema(entitySchema, propertyName); if (propertySchema == null) { continue; } if (propertySchema.Attribute(SchemaVocab.Column) == null) { continue; } foreach (ValidationAttribute validationAttribute in propertySchema.CreateValidationAttributes()) { if (!validationAttribute.IsValid(propertyValue)) { string dispalyName = SchemaHelper.GetDisplayName(propertySchema); string errorMessage = validationAttribute.FormatErrorMessage(dispalyName); ValidationResult validationResult = new ValidationResult(errorMessage, new List <string>() { executeCommand.Path }); validationResults.Add(validationResult); } } } return(validationResults); }
public DataViewRowCursor[] GetRowCursorSet(IEnumerable <DataViewSchema.Column> columnsNeeded, int n, Random rand = null) { ComputeNearestNeighbors(); _host.AssertValue(_input, "_input"); var schema = _input.Schema; if (columnsNeeded.Where(c => c.Index == _input.Schema.Count).Any()) { var newColumns = PredicatePropagation(columnsNeeded); var oldCols = SchemaHelper.ColumnsNeeded(newColumns, schema); var featureIndex = SchemaHelper.GetColumnIndexDC(Schema, _args.column); var res = _input.GetRowCursorSet(oldCols, n, rand) .Select(c => new NearestNeighborsCursor(c, this, newColumns, featureIndex)).ToArray(); return(res); } else { // The new column is not required. We do not need to compute it. But we need to keep the same schema. var oldCols = SchemaHelper.ColumnsNeeded(columnsNeeded, schema); return(_input.GetRowCursorSet(oldCols, n, rand).Select(c => new SameCursor(c, Schema)).ToArray()); } }
private DeTrendTransform(IHost host, ModelLoadContext ctx, IDataView input) : base(host, input) { Host.CheckValue(input, "input"); Host.CheckValue(ctx, "ctx"); _args = new Arguments(); _args.Read(ctx, Host); ctx.LoadModel <IPredictor, SignatureLoadModel>(host, out _trend, "trend"); if (_args.columns == null || _args.columns.Length != 1) { Host.ExceptUserArg(nameof(_args.columns), "One column must be specified."); } int index = SchemaHelper.GetColumnIndex(input.Schema, _args.columns[0].Source); _schema = ExtendedSchema.Create(new ExtendedSchema(input.Schema, new[] { _args.columns[0].Name }, new[] { NumberDataViewType.Single /*input.Schema.GetColumnType(index)*/ })); _lock = new object(); _transform = BuildTransform(_trend); }
public ResampleTransform(IHostEnvironment env, Arguments args, IDataView input) { Contracts.CheckValue(env, "env"); _host = env.Register("ResampleTransform"); _host.CheckValue(args, "args"); // Checks values are valid. _host.CheckValue(input, "input"); _host.Check(args.lambda > 0, "lambda must be > 0"); _input = input; _args = args; _cacheReplica = null; if (!string.IsNullOrEmpty(_args.column)) { int index = SchemaHelper.GetColumnIndex(_input.Schema, _args.column); if (string.IsNullOrEmpty(_args.classValue)) { throw _host.Except("Class value cannot be null."); } } _transform = CreateTemplatedTransform(); }
public void Mutation_UpdatePosition() { Database.WriteAsync(realm => realm.Add(new Position { Id = 40, Name = "Quản trị viên", IsActive = true })).Wait(); SchemaHelper.Execute( @"/_GraphQL/Position/mutation.updatePosition.gql", @"/_GraphQL/Position/mutation.updatePosition.schema.json", new { input = new { id = 40, name = "Tên quyền", permissionCleaning = true, permissionGetAccountingVoucher = true, permissionGetHouseKeeping = true, permissionGetMap = true, permissionGetPatron = true, permissionGetRate = true, permissionGetService = true, permissionManageEmployee = true, permissionManageRentingRoom = false, permissionManageMap = true, permissionManagePatron = true, permissionManagePatronKind = true, permissionManagePosition = true, permissionManageRate = true, permissionManageService = true } }, p => p.PermissionManagePosition = true ); }
public void Mutation_CheckOut_InvalidEmployee() { Database.WriteAsync(realm => { realm.Add(new Employee { Id = "nhanvien_1", Address = "Địa chỉ", IsActive = true, Birthdate = DateTimeOffset.Now, Email = "*****@*****.**", Gender = true, Name = "Quản trị viên", IdentityCard = "123456789", Password = CryptoHelper.Encrypt("12345678"), PhoneNumber = "+84 0123456789", Position = PositionBusiness.Get(1), StartingDate = DateTimeOffset.Now }); realm.Add(new Booking { Id = 22, Status = (int)Booking.StatusEnum.RequestedCheckOut, EmployeeBooking = EmployeeDataAccess.Get("admin"), EmployeeCheckIn = EmployeeDataAccess.Get("admin"), EmployeeCheckOut = EmployeeDataAccess.Get("nhanvien_1"), Bill = BillDataAccess.Get(1), Room = RoomDataAccess.Get(1) }); }).Wait(); SchemaHelper.ExecuteAndExpectError( "Nhân viên không được phép check-out", @"/_GraphQL/Booking/mutation.checkOut.gql", new { id = 22 }, p => p.PermissionManageRentingRoom = true ); }
public void Mutation_UpdateEmployee_InvalidId() { SchemaHelper.ExecuteAndExpectError( "Không tồn tại nhân viên này", @"/_GraphQL/Employee/mutation.updateEmployee.gql", new { input = new { id = "không tồn tại", name = "Tên nhân viên", identityCard = "12345678", gender = true, email = "*****@*****.**", phoneNumber = "123456789", address = "164/54", birthdate = "04-04-1996", startingDate = "10-10-2015", position = new { id = 1 } } }, p => p.PermissionManageEmployee = true ); }
public void Mutation_UpdateFloor_InvalidFloor_InActive() { Database.WriteAsync(realm => realm.Add(new Floor { Id = 41, Name = "Tầng tạo ra để cập nhật", IsActive = false })).Wait(); SchemaHelper.ExecuteAndExpectError( "Tầng 41 đã ngưng hoạt động. Không thể cập nhật/xóa!", @"/_GraphQL/Floor/mutation.updateFloor.gql", new { input = new { id = 41, name = "Tên tầng đã được cập nhật" } }, p => p.PermissionManageMap = true ); }
public void Mutation_UpdateFloor() { Database.WriteAsync(realm => realm.Add(new Floor { Id = 40, Name = "Tầng tạo ra để cập nhật", IsActive = true })).Wait(); SchemaHelper.Execute( @"/_GraphQL/Floor/mutation.updateFloor.gql", @"/_GraphQL/Floor/mutation.updateFloor.schema.json", new { input = new { id = 40, name = "Tên tầng đã được cập nhật" } }, p => p.PermissionManageMap = true ); }
public override void ExecuteDdlCommands(IEnumerable <string> commands, string connStr) { using (var con = new SqlConnection(connStr)) { con.Open(); var cmd = con.CreateCommand(); cmd.CommandTimeout = 0; using (var trans = con.BeginTransaction(IsolationLevel.Serializable)) { cmd.Transaction = trans; foreach (var command in commands) { cmd.CommandText = command; SchemaHelper.SafeRunCommand(command, () => cmd.ExecuteNonQuery()); } trans.Commit(); } } }
public void Mutation_CreateRoom() { SchemaHelper.Execute( @"/_GraphQL/Room/mutation.createRoom.gql", @"/_GraphQL/Room/mutation.createRoom.schema.json", new { input = new { name = "Phòng 2", roomKind = new { id = 1 }, floor = new { id = 1 } } }, p => p.PermissionManageMap = true ); }
ValueGetter <VBuffer <float> > GetGetter(ScalingFactor scales) { var getter = _inputCursor.GetGetter <float>(SchemaHelper._dc(scales.columnId, _inputCursor)); float value = 0f; return((ref VBuffer <float> dst) => { getter(ref value); if (1 != scales.mean.Length) { throw _parent._host.Except("Mismatch dimension {0} for destination != {1} for scaling vectors.", dst.Length, scales.mean.Length); } if (dst.Length != 1) { dst = new VBuffer <float>(1, new[] { value }); } else { dst.Values[0] = value; } scales.Update(ref dst); }); }
public void Mutation_CreateRoom_InvalidFloor() { SchemaHelper.ExecuteAndExpectError( "Tầng có Id: 100 không hợp lệ!", @"/_GraphQL/Room/mutation.createRoom.gql", new { input = new { name = "Phòng 2", roomKind = new { id = 1 }, floor = new { id = 100 } } }, p => p.PermissionManageMap = true ); }
public void Mutation_CreateRoom_InvalidRoomKind() { SchemaHelper.ExecuteAndExpectError( "Mã loại phòng không tồn tại", @"/_GraphQL/Room/mutation.createRoom.gql", new { input = new { name = "Phòng 2", roomKind = new { id = 100 }, floor = new { id = 1 } } }, p => p.PermissionManageMap = true ); }
public RowCursor[] GetRowCursorSet(Func <int, bool> predicate, int n, Random rand = null) { var host = new ConsoleEnvironment().Register("Estimate n threads"); n = DataViewUtils.GetThreadCount(host, n); if (n <= 1) { return new RowCursor[] { GetRowCursor(predicate, rand) } } ; else { var cursors = Source.GetRowCursorSet(i => predicate(i) || predicate(SchemaHelper.NeedColumn(_columnMapping, i)), n, rand); for (int i = 0; i < cursors.Length; ++i) { cursors[i] = new AddRandomCursor(this, cursors[i]); } return(cursors); } }
public void Mutation_UpdatePatronKind() { Database.WriteAsync(realm => realm.Add(new PatronKind { Id = 20, Name = "Tên loại khách hàng", Description = "Mô tả loại khách hàng" })).Wait(); SchemaHelper.Execute( @"/_GraphQL/PatronKind/mutation.updatePatronKind.gql", @"/_GraphQL/PatronKind/mutation.updatePatronKind.schema.json", new { input = new { id = 20, name = "Loại khách 2", description = "Loại khách 2" } }, p => p.PermissionManagePatronKind = true ); }
public void Mutation_CreateServicesDetail_InvalidService() { SchemaHelper.ExecuteAndExpectError( "Mã dịch vụ không tồn tại", @"/_GraphQL/ServicesDetail/mutation.createServicesDetail.gql", new { input = new { number = 1, service = new { id = 100 }, booking = new { id = 1 } } }, p => p.PermissionManageRentingRoom = true ); }
protected override void ExecuteDdlCommands(IEnumerable <string> commands, string connStr) { using (var con = new OleDbConnection(connStr)) { con.Open(); var cmd = con.CreateCommand(); cmd.CommandTimeout = 0; using (var trans = con.BeginTransaction()) { cmd.Transaction = trans; foreach (var command in commands) { cmd.CommandText = command + @";"; SchemaHelper.SafeRunCommand(command, () => cmd.ExecuteNonQuery()); } trans.Commit(); } } }
private static bool TryCreateSchema( IReadOnlyList <GraphQLFile> files, Dictionary <ISyntaxNode, string> fileLookup, ICollection <IError> errors, bool strictValidation, [NotNullWhen(true)] out ISchema?schema) { try { schema = SchemaHelper.Load(files, strictValidation); return(true); } catch (SchemaException ex) { foreach (ISchemaError error in ex.Errors) { errors.Add(error.SchemaError(fileLookup)); } schema = null; return(false); } }
public void Mutation_CreateServicesDetail() { SchemaHelper.Execute( @"/_GraphQL/ServicesDetail/mutation.createServicesDetail.gql", @"/_GraphQL/ServicesDetail/mutation.createServicesDetail.schema.json", new { input = new { number = 1, service = new { id = 1 }, booking = new { id = 1 } } }, p => p.PermissionManageRentingRoom = true ); }
public void Mutation_UpdateServicesDetail_InvalidService_InActive() { Database.WriteAsync(realm => { realm.Add(new Service { Id = 202, IsActive = false, Name = "Tên dịch vụ", Unit = "Đơn vị" }); realm.Add(new ServicesDetail { Id = 21, Booking = BookingBusiness.Get(1), Service = ServiceBusiness.Get(1), Number = 10 }); }).Wait(); SchemaHelper.ExecuteAndExpectError( "Dịch vụ 202 đã ngừng cung cấp", @"/_GraphQL/ServicesDetail/mutation.updateServicesDetail.gql", new { input = new { id = 21, number = 2, service = new { id = 202 } } }, p => p.PermissionCleaning = true ); }
public PolynomialState(IHostEnvironment host, IDataView input, Arguments args, Func <TInput, TInput, TInput> multiplication) { _host = host.Register("PolynomialState"); _host.CheckValue(input, "input"); _input = input; // _lock = new object(); _args = args; _multiplication = multiplication; var column = _args.columns[0]; var schema = input.Schema; using (var ch = _host.Start("PolynomialState")) { _inputCol = SchemaHelper.GetColumnIndexDC(schema, column.Source); var type = schema[_inputCol.Index].Type; if (!type.IsVector()) { throw _host.Except("Input column type must be a vector."); } int dim = type.AsVector().DimCount(); if (dim > 1) { throw _host.Except("Input column type must be a vector of one dimension."); } int size = dim > 0 ? type.AsVector().GetDim(0) : 0; if (size > 0) { size = TotalCumulated[_args.degree](size); } ch.Trace("PolynomialTransform {0}->{1}.", dim, size); // We extend the input schema. The new type has the same type as the input. _schema = ExtendedSchema.Create(new ExtendedSchema(input.Schema, new[] { column.Name }, new[] { new VectorDataViewType(type.AsVector().ItemType(), size) })); } }
protected Tuple <TLabel, TLabel> MinMaxLabel <TLabel>(MultiToBinaryTransform tr, int index) where TLabel : IComparable <TLabel> { using (var cursor = tr.GetRowCursor(tr.Schema.Where(c => c.Index == index).ToArray())) { var getter = cursor.GetGetter <TLabel>(SchemaHelper._dc(index, cursor)); TLabel cl = default(TLabel), max = default(TLabel), min = default(TLabel); bool first = true; while (cursor.MoveNext()) { getter(ref cl); if (first || cl.CompareTo(max) == 1) { max = cl; } if (first || cl.CompareTo(max) == -1) { min = cl; } first = false; } return(new Tuple <TLabel, TLabel>(min, max)); } }
/// <summary> /// Create the internal transform (not serialized in the zip file). /// </summary> private IDataTransform CreateTemplatedTransform() { IDataView view = Source; var schema = _input.Schema; int index; for (int i = 0; i < _args.columns.Length; ++i) { index = SchemaHelper.GetColumnIndex(schema, _args.columns[i].Source); var typeCol = schema[index].Type; if (typeCol.IsVector()) { throw _host.Except("Expected a number as input."); } switch (typeCol.RawKind()) { case DataKind.R4: view = new PassThroughTransform(_host, new PassThroughTransform.Arguments(), LambdaColumnMapper.Create(_host, "R42R4", view, _args.columns[i].Source, _args.columns[i].Name, NumberType.R4, NumberType.R4, (in float src, ref float dst) => { dst = src; })); break;
public void Inject_Into_ListView() { var helper = new SchemaHelper(); var element = new DictionaryNode("Element"); element.SetAttribute("Name", ModelElement.Application.ToString()); var childNode = element.AddChildNode("Element"); childNode.SetAttribute("Name", ModelElement.Views.ToString()); var addChildNode = childNode.AddChildNode("Element"); addChildNode.SetAttribute("Name", ModelElement.ListView.ToString()); addChildNode.AddChildNode("Element1"); DictionaryNode dictionaryNode=helper.Inject(@"<Element1/>", ModelElement.ListView); Assert.AreEqual(element.ToXml(), dictionaryNode.ToXml()); }
public override Schema GetSchema() { const string s = @"<Attribute Name=""" + IsCloneAbleAttributeName + @""" Choice=""True,False""/>"; var helper=new SchemaHelper(); var schema = new Schema(helper.Inject(s, ModelElement.ListView)); return schema; }
public override Schema GetSchema() { var helper = new SchemaHelper(); DictionaryNode dictionaryNode = helper.Inject(@"<Attribute Name=""" + DescribeRunTimeMembersAttributeName + @""" Choice=""True,False""/>", ModelElement.Class); return new Schema(dictionaryNode); }