public static TableEntity Get(string data) { TableEntity entity = new TableEntity(); string[] lines = data.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); if (lines.Count<string>() < 1) throw new Exception(string.Format("'{0}' is not a valid input", data)); foreach (string line in lines) { string[] values = line.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries); Debug.Assert(values.Length == 2); if (values.Count<string>() != 2) throw new Exception(string.Format("'{0}' is not a valid input", line)); if (values[0] == "PartitionKey") entity.PartitionKey = values[1]; else if (values[0] == "RowKey") entity.RowKey = values[1]; else entity[values[0]] = values[1]; } if (string.IsNullOrEmpty(entity.PartitionKey)) entity.PartitionKey = "1"; if (string.IsNullOrEmpty(entity.RowKey)) entity.RowKey = Guid.NewGuid().ToString(); return entity; }
//private void InitSingle(TableEntity entity, object value) //{ // IComponent c = value as IComponent; // ComponentAttribute ca = new ComponentAttribute(c); // List<FieldAttributeInfo> attInfos = AttributeHelper.GetComponentField(ca); // List<string> titles = new List<string>(); // List<string> values = new List<string>(); // foreach (FieldAttributeInfo t in attInfos) // { // if (string.IsNullOrEmpty(t.Title)) // { // titles.Add(t.Name); // } // else // { // titles.Add(t.Title); // } // try // { // object o = ca.Get(t.Name); // if (o != null) // { // values.Add(o.ToString()); // } // else // { // values.Add(string.Empty); // } // } // catch // { // values.Add(string.Empty); // } // } // entity.Value.Add(titles); // entity.Value.Add(values); //} private void InitList(TableEntity entity, object value) { IEnumerable lt = value as IEnumerable; List<string> titles = new List<string>(); List<string> values =null; bool b = false; foreach (var c in lt) { values = new List<string>(); TypeAttribute ca = c as TypeAttribute; if (ca != null) { List<FieldAttributeInfo> attInfos = AttributeHelper.GetComponentField(ca); foreach (FieldAttributeInfo t in attInfos) { if (!b) { if (string.IsNullOrEmpty(t.Title)) { titles.Add(t.Name); } else { titles.Add(t.Title); } } try { object o = ca.Get(t.Name); if (o != null) { values.Add(o.ToString()); } else { values.Add(string.Empty); } } catch { values.Add(string.Empty); } } if (!b) { entity.Value.Add(titles); b = true; } entity.Value.Add(values); } } }
public void InsertTableEntity(TableEntity condition_entity) { try { DianDao.InsertEntity(condition_entity); } catch (Exception ex) { throw new DianBizException("插入店数据出错!", ex); } }
public void DeleteTableEntity(TableEntity condition_entity) { try { DianDao.DeleteEntity(condition_entity); } catch (Exception ex) { throw new DianBizException("删除店数据出错!", ex); } }
public static async Task LaunchScheduleDeleteQueue( [QueueTrigger("ScheduleDeleteRequests", Connection = "ScheduleStorageAccount")] string id, [Table("LaunchSchedules", Connection = "ScheduleStorageAccount")] CloudTable scheduleTable, TraceWriter log) { log.Info($"Schedule Delete Request Item Processed: {id}"); TableEntity entity = new TableEntity("Schedules", id); TableOperation deleteOperation = TableOperation.Delete(entity); await scheduleTable.ExecuteAsync(deleteOperation); log.Info($"Schedule Successfully Deleted."); }
public async Task Delete(String TableName, string partitionKey, string rowKey) { //Item TableEntity item = await GetItem(TableName, partitionKey, rowKey); //Table CloudTable table = await GetTableAsync(TableName); //Operation TableOperation operation = TableOperation.Delete(item); //Execute await table.ExecuteAsync(operation); }
static Func <DynamicTableEntity, T> BuildEntity <T>() where T : class, new() { if (typeof(T) == typeof(DynamicTableEntity)) { return(e => e as T); } return(e => { var t = new T(); TableEntity.ReadUserObject(t, e.Properties, new OperationContext()); return t; }); }
public void ConstructorEmpty() { var model = new TableEntity(); var result = model.Validate(); Assert.False(result.Any()); Assert.Null(model.Description); Assert.Equal(decimal.Zero, model.Id); Assert.Null(model.SyncId); Assert.Equal(string.Empty, model.TableName); Assert.Equal(char.MinValue, model.Type); }
public async Task WriteNewUser(UserModel user, List<GroupModel>, groups) { //...assume user table connection is created var entity = new DynamicTableEntity(partitionKey, rowKey); entity.Properties = TableEntity.Flatten(user, new OperationContext()); await userTable.ExecuteAsync(TableOperation.Insert(user)); //...assume group table connection is created groups.ForEach(async g => { var groupsEntity = new DynamicTableEntity(user.UserId, Guid.NewGuid().ToString()); groupsEntity.Properties = TableEntity.Flatten(g, new OperationContext()); await groupsTable.ExecuteAsync(TableOperation.Insert(groupsEntity)); }); }
private static byte[] ReadBinaryData(TableEntity entity) { var dataChunks = ReadBinaryDataChunks(entity).ToArray(); var dataSize = dataChunks.Select(d => d.Length).Sum(); var result = new byte[dataSize]; var startIndex = 0; foreach (var dataChunk in dataChunks) { Array.Copy(dataChunk, 0, result, startIndex, dataChunk.Length); startIndex += dataChunk.Length; } return(result); }
/// <inheritdoc /> public async Task <TableResult> DeleteTableEntityAsync(string tableName, TableEntity entity) { // Delete item (the ETAG is required here!). entity.ETag = "*"; // Create the CloudTable object that represents the tableName table. CloudTable table = cloudTableClient.GetTableReference(tableName); // Create the TableOperation that insert or update the entity. TableOperation deleteOperation = TableOperation.Delete(entity); // Execute the batch operation. return(await table.ExecuteAsync(deleteOperation)); }
public async Task <TableEntity> AddDataToStorage(TableEntity entity, string tableName) { var insertOperation = TableOperation.InsertOrMerge(entity); var table = _tableClient.GetTableReference(tableName); if (!await table.ExistsAsync()) { await table.CreateAsync(); } var result = await table.ExecuteAsync(insertOperation); return(result.Result as TableEntity); }
private static async Task <List <string> > GetUsersFromTable(CloudTable cloudTable) { TableQuery <TableEntity> idQuery = new TableQuery <TableEntity>(); List <string> users = new List <string>(); foreach (TableEntity entity in await cloudTable.ExecuteQuerySegmentedAsync(idQuery, null)) { TableEntity user = new TableEntity(); user.PartitionKey = entity.PartitionKey; users.Add(user.PartitionKey); } return(users); }
public static async Task <HttpResponseMessage> DeleteLaunchSchedule( [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "v1/launch/schedules/{id}")] HttpRequestMessage req, [Table("LaunchSchedules", Connection = "ScheduleStorageAccount")] CloudTable scheduleTable, string id, TraceWriter log) { TableEntity entity = new TableEntity("Schedules", id); TableOperation deleteOperation = TableOperation.Delete(entity); await scheduleTable.ExecuteAsync(deleteOperation); return(req.CreateResponse(HttpStatusCode.NoContent)); }
/// <summary> /// Serialize to Azure storage format in either binary or JSON format. /// </summary> /// <param name="grainState">The grain state data to be serialized</param> /// <param name="entity">The Azure table entity the data should be stored in</param> /// <remarks> /// See: /// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx /// for more on the JSON serializer. /// </remarks> internal void ConvertToStorageFormat(object grainState, TableEntity entity) { int dataSize; IEnumerable <object> properties; string basePropertyName; if (this.options.UseJson) { // http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm string data = Newtonsoft.Json.JsonConvert.SerializeObject(grainState, this.JsonSettings); if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("Writing JSON data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); } // each Unicode character takes 2 bytes dataSize = data.Length * 2; properties = SplitStringData(data).Select(t => (object)t); basePropertyName = STRING_DATA_PROPERTY_NAME; } else { // Convert to binary format byte[] data = this.serializer.SerializeToArray(grainState); if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("Writing binary data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); } dataSize = data.Length; properties = SplitBinaryData(data).Select(t => (object)t); basePropertyName = BINARY_DATA_PROPERTY_NAME; } CheckMaxDataSize(dataSize, MAX_DATA_CHUNK_SIZE * MAX_DATA_CHUNKS_COUNT); foreach (var keyValuePair in properties.Zip(GetPropertyNames(basePropertyName), (property, name) => new KeyValuePair <string, object>(name, property))) { entity[keyValuePair.Key] = keyValuePair.Value; } }
public TableSchema(TableEntity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } Entity = entity; Columns = new List <DBColumn>(); Foreigns = new List <DBForeign>(); SetTable(); InitialColumns(); InitialForeigns(); Ready = true; }
public async Task <TableEntity> InsertOrMerge(CloudTable table, TableEntity tableEntity) { TableOperation insertorMergeOp = TableOperation.InsertOrMerge(tableEntity); TableResult result = await table.ExecuteAsync(insertorMergeOp); TableEntity inserted = result.Result as TableEntity; if (result.RequestCharge.HasValue) { Console.WriteLine($"Request charge of insert or merge operation: {result.RequestCharge}"); } return(inserted); }
public static Task ToTaskEntity(this TableEntity entity) { return(new Task { Id = Guid.Parse(entity[nameof(Task.Id)].ToString()), Title = entity[nameof(Task.Title)]?.ToString(), Description = entity[nameof(Task.Description)]?.ToString(), User = new Task.UserDescriptor { UserId = entity[nameof(Task.UserDescriptor.UserId)]?.ToString(), UserName = entity[nameof(Task.UserDescriptor.UserName)]?.ToString() }, Status = (Task.TaskStatus)Enum.Parse(typeof(Task.TaskStatus), entity[nameof(Task.Status)].ToString()) }); }
public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext) { var properties = TableEntity.WriteUserObject(Value, operationContext); var additionalMappings = GetAdditionPropertyMappings(Value, operationContext); if (additionalMappings.Count > 0) { WriteAdditionalProperties(additionalMappings, properties); } WriteValues(properties, operationContext); return(properties); }
public void DataBind(string tableID) { CodeBuilderService service = ServiceHelper.GetCodeBuilderService(); if (string.IsNullOrEmpty(tableID)) { DataTable dt = service.GetTableDataTable(Global.GetCurrentProjectID()); this.filterCheckList.DataBind(dt, "TableName"); } else { TableEntity table = service.GetTableById(tableID); this.filterCheckList.AddItem(table.TableName, true); } }
public static async Task <bool> DeleteEntity(TableEntity entity, string tableName) { try { var table = ConnectToTable(tableName); var delete = TableOperation.Delete(entity); await table.ExecuteAsync(delete); return(true); } catch (Exception ex) { return(false); } }
public static async Task <bool> InsertEntity(TableEntity entity, string tableName) { try { var table = ConnectToTable(tableName); var insert = TableOperation.Insert(entity); await table.ExecuteAsync(insert); return(true); } catch (Exception ex) { return(false); } }
private static IEventEntity <Person> PersonEventResolver(string partitionKey, string rowKey, DateTimeOffset timeStamp, IDictionary <string, EntityProperty> props, string etag) { var type = props["EventType"].StringValue; Type t = ConvertNameToEntityType(type); TableEntity evnt = FormatterServices.GetUninitializedObject(t) as TableEntity; evnt.PartitionKey = partitionKey; evnt.RowKey = rowKey; evnt.Timestamp = timeStamp; evnt.ETag = etag; evnt.ReadEntity(props, null); return(evnt as IEventEntity <Person>); }
/// <summary> /// Move the table down in the list of tables in this node /// </summary> /// <param name="tableToMove"></param> public void MoveTableDown(TableEntity tableToMove) { if (_tables.Contains(tableToMove)) { int currentIndex = _tables.IndexOf(tableToMove); int newIndex = currentIndex + 1; if (newIndex >= _tables.Count) { return; } _tables.Move(currentIndex, newIndex); OnPropertyChanged("Tables"); } }
public static T ReadObject <T>(this IDictionary <string, EntityProperty> properties, string prefix) where T : new() { var keyPrefix = $"{prefix}_"; var nestedProperties = properties.Where(kvp => kvp.Key.StartsWith(keyPrefix)) .ToDictionary(kvp => kvp.Key.Replace(keyPrefix, string.Empty), kvp => kvp.Value); if (!nestedProperties.Any()) { return(default(T)); } var instance = TableEntity.ConvertBack <T>(nestedProperties, null); return(instance); }
private PredictionSet MapTableEntityToPredictionSetModel(TableEntity entity) { PredictionSet predictionSet = new PredictionSet(); predictionSet.Name = entity.RowKey; if (entity["Description"] != null) { predictionSet.Description = entity["Description"].ToString(); } if (entity["RuleUrl"] != null) { predictionSet.RuleUrl = entity["RuleUrl"].ToString(); } return(predictionSet); }
public TableControl(TableEntity tableEntity, Enums.TableType tableType, int posX, int posY) { if (tableEntity != null) { this.tableEntity = tableEntity; } else { this.tableEntity = new TableEntity(tableType); } switch (tableType) { case (Enums.TableType.Source_Table): { this.tableColor = Color.FromArgb(192, 57, 43); this.textColor = Color.White; this.hoverColor = Color.FromArgb(231, 76, 60); break; }; case (Enums.TableType.Extraction_Table): { this.tableColor = Color.FromArgb(44, 62, 80); this.textColor = Color.White; this.hoverColor = Color.FromArgb(52, 73, 94); break; }; case (Enums.TableType.Load_Table): { this.tableColor = Color.FromArgb(41, 128, 185); this.textColor = Color.White; this.hoverColor = Color.FromArgb(52, 152, 219); break; }; case (Enums.TableType.Destination_Table): { this.tableColor = Color.FromArgb(211, 84, 0); this.textColor = Color.White; this.hoverColor = Color.FromArgb(230, 126, 34); break; }; } //this.SetBounds(posX, posY, 100, 20); }
public List<TableEntity> GetTableEntityList(TableEntity condition_entity) { try { GenericWhereEntity<TableEntity> where_entity = new GenericWhereEntity<TableEntity>(); if (condition_entity.TABLE_ID != null) where_entity.Where(n => (n.TABLE_ID == condition_entity.TABLE_ID)); if (condition_entity.RESTAURANT_ID != null) where_entity.Where(n => (n.RESTAURANT_ID == condition_entity.RESTAURANT_ID)); return DianDao.ReadEntityList(where_entity); } catch (Exception ex) { throw new DianBizException("获取店的数据出错!", ex); } }
public static async Task <bool> ReplaceEntity(TableEntity entity, string tableName) { try { var table = ConnectToTable(tableName); entity.ETag = "*"; var replace = TableOperation.Replace(entity); await table.ExecuteAsync(replace); return(true); } catch (Exception ex) { return(false); } }
public void Convert_IfETagIsReadOnly_PopulatesETag() { // Arrange string expectedETag = "abc"; IConverter <PocoWithReadOnlyETag, TableEntity> product = CreateProductUnderTest <PocoWithReadOnlyETag>(); PocoWithReadOnlyETag input = new PocoWithReadOnlyETag { WriteETag = expectedETag }; // Act TableEntity actual = product.Convert(input); // Assert Assert.NotNull(actual); Assert.AreEqual(new ETag(expectedETag), actual.ETag); }
public void Convert_IfRowKeyIsReadOnly_PopulatesRowKey() { // Arrange const string expectedRowKey = "RK"; IConverter <PocoWithReadOnlyRowKey, TableEntity> product = CreateProductUnderTest <PocoWithReadOnlyRowKey>(); PocoWithReadOnlyRowKey input = new PocoWithReadOnlyRowKey { WriteRowKey = expectedRowKey }; // Act TableEntity actual = product.Convert(input); // Assert Assert.NotNull(actual); Assert.AreSame(expectedRowKey, actual.RowKey); }
/// <summary> /// Create a TableEntity and get all its columns /// </summary> /// <param name="tableSchema">schema name of the table to get</param> /// <param name="tableName">tableName of the table to get</param> /// <returns></returns> public TableEntity GetTableAndColumns(string tableSchema, string tableName) { using (ColumnEntityDataAccess colDa = new ColumnEntityDataAccess(this._connectionString)) { TableEntity table = GetOne(string.Format("select Table_Name, Table_Schema from information_Schema.Tables WITH(NOLOCK) where table_schema = '{0}' and table_name = '{1}'", tableSchema, tableName), CreateTableEntity); table.AddColumns(colDa.GetAllColumnsForTable(table)); // // TODO: Dont add these foreign key generators here. Should be handled more central foreach (var column in table.Columns.Where(x => x.IsForeignKey)) { GetForeignKeyGeneratorsForColumn(column); } table.RefreshWarnings(); return(table); } }
public void ShouldAddColumnToTable() { TableEntity table = new TableEntity("dbo", "Customer"); var column = DatabaseEntityFactory.CreateColumnEntity( "CustomerName", new ColumnDataTypeDefinition("varchar(500)", true), false, 2, false, string.Empty, null); table.AddColumn(column); Assert.That(table.Columns.Contains(column)); }
public void Convert_PopulatesPartitionKey() { // Arrange const string expectedPartitionKey = "PK"; IConverter <PocoWithPartitionKey, TableEntity> product = CreateProductUnderTest <PocoWithPartitionKey>(); PocoWithPartitionKey input = new PocoWithPartitionKey { PartitionKey = expectedPartitionKey }; // Act TableEntity actual = product.Convert(input); // Assert Assert.NotNull(actual); Assert.AreSame(expectedPartitionKey, actual.PartitionKey); }
private async Task <bool> InsertAlertLevelsOperation(int newLevel, string rowKey) { if (newLevel <= 0) { return(false); } TableEntity entityToBeInserted = new TableEntity() { PartitionKey = newLevel.ToString("D3"), RowKey = rowKey, ETag = "*" //conflicts are of no concern }; await _alertsTable.ExecuteAsync(TableOperation.InsertOrReplace(entityToBeInserted)); return(true); }
public BaseCptEntity ToModel(string title, string name, object value) { TableEntity entity = new TableEntity(); entity.Value = new List<List<string>>(); //if (value is IComponent) //{ // InitSingle(entity, value); // return entity; //} if (value is IList) { InitList(entity, value); return entity; } return entity; }
private void Save() { try { ITable biz = new TableBiz(); var entity = new TableEntity(); entity.TABLE_NAME = this.tTableName.Value; entity.RESTAURANT_ID = base.ParseInt(this.ddlRestaurant.SelectedValue); if (CurOperation == "add") biz.InsertTableEntity(entity); else if (CurOperation == "edit") { entity.TABLE_ID = CurId; biz.UpdateTableEntity(entity); } AlertAndTransfer("保存成功!", base.UrlReferrer); } catch (Exception ex) { this.lMsg.InnerText = "保存失败,原因:" + ex.ToString(); } }
/// <summary> /// 2.3: Update the Mapping Associations and check the end points. /// ///<AssociationSetMapping Name="aspnet_UsersInRoles" TypeName="PetShopModel.aspnet_UsersInRoles" StoreEntitySet="aspnet_UsersInRoles"> /// <EndProperty Name="aspnet_Roles"> /// <ScalarProperty Name="RoleId" ColumnName="RoleId" /> /// </EndProperty> /// <EndProperty Name="aspnet_Users"> /// <ScalarProperty Name="UserId" ColumnName="UserId" /> /// </EndProperty> ///</AssociationSetMapping> /// /// </summary> /// <param name="entity">The Entity</param> private void CreateMappingAssociations(TableEntity entity) { // <AssociationSetMapping Name="aspnet_UsersInRoles" TypeName="PetShopModel.aspnet_UsersInRoles" StoreEntitySet="aspnet_UsersInRoles"> #region Validate that an AssociationSetMapping Exists in the MappingEntityContainer. foreach (var association in entity.Associations) { IEntity principalEntity; IEntity dependentEntity; bool isParentEntity; string key; string toRole; string fromRole; ResolveConceptualAssociationValues(association, out principalEntity, out dependentEntity, out isParentEntity, out key, out toRole, out fromRole); if (!(association.AssociationType == AssociationType.ManyToMany && association.IntermediaryAssociation != null) || principalEntity is TableEnumEntity || dependentEntity is TableEnumEntity) continue; var typeName = association.Entity.EntityKeyName; var associationSetMapping = MappingEntityContainer.AssociationSetMappings.Where(e => e.Name.Equals(association.Entity.EntityKeyName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (associationSetMapping == null) { associationSetMapping = new AssociationSetMapping { Name = association.Entity.EntityKeyName, EndProperties = new List<EndProperty>() }; MappingEntityContainer.AssociationSetMappings.Add(associationSetMapping); } else if (!String.IsNullOrEmpty(associationSetMapping.TypeName)) { typeName = associationSetMapping.TypeName.Replace(String.Format("{0}.", ConceptualSchema.Namespace), ""); typeName = typeName.Equals(association.Entity.EntityKeyName, StringComparison.OrdinalIgnoreCase) ? association.Entity.EntityKeyName : typeName; } // Set or sync the default values. associationSetMapping.Name = association.Entity.EntityKeyName; associationSetMapping.TypeName = String.Concat(ConceptualSchema.Namespace, ".", typeName); associationSetMapping.StoreEntitySet = association.Entity.EntityKeyName; _mappingAssociationNames[association.AssociationKeyName] = typeName; _mappingAssociationNames[association.IntermediaryAssociation.AssociationKeyName] = typeName; var properties = new List<EndProperty>(); //<EndProperty Name="aspnet_Roles"> // <ScalarProperty Name="RoleId" ColumnName="RoleId" /> //</EndProperty> var principalEnd = associationSetMapping.EndProperties.Where(e => e.Name.Equals(principalEntity.EntityKeyName) || e.Name.Equals(ResolveEntityMappedName(principalEntity.EntityKey(), principalEntity.Name))).FirstOrDefault() ?? new EndProperty() { Name = ResolveEntityMappedName(principalEntity.EntityKey(), principalEntity.Name) }; principalEnd.Name = ResolveEntityMappedName(principalEntity.EntityKey(), principalEntity.Name); MergeScalarProperties(principalEnd, association); properties.Add(principalEnd); var dependentEnd = associationSetMapping.EndProperties.Where(e => !e.Name.Equals(principalEnd.Name)).FirstOrDefault() ?? new EndProperty() { Name = ResolveEntityMappedName(dependentEntity.EntityKey(), dependentEntity.Name) }; dependentEnd.Name = ResolveEntityMappedName(dependentEntity.EntityKey(), dependentEntity.Name); if (dependentEnd.Name.Equals(principalEnd.Name)) dependentEnd.Name += 1; MergeScalarProperties(dependentEnd, association.IntermediaryAssociation); properties.Add(dependentEnd); associationSetMapping.EndProperties = properties; } #endregion }
static void Main() { // // var type = typeof(FunkyAttributesEnum); // var memInfo = type.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString()); // var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), // false); // var description = ((DescriptionAttribute)attributes[0]).Description; // // var type = typeof (TableEntity.Fields); // var memInfo = type.GetMember(TableEntity.Fields.Id.ToString()); // var attributes = memInfo[0].GetCustomAttributes(typeof (DBType), // false); // var description = ((DBType) attributes[0]).Type; // Console.WriteLine(description); // // //// // // System.Reflection.MemberInfo info = typeof(TableEntity.Fields); // var memInfo = info.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString()); // // // // object[] attributes = info.GetCustomAttributes(true); // for (int i = 0; i < attributes.Length; i++) // { // System.Console.WriteLine(attributes[i]); // } // Console.ReadKey(); // return; // NpgsqlConnection con = new NpgsqlConnection("Server=localhost;Port=5432;User=postgres;Password=postgres;Database=postgres;"); // con.Open(); //// Server=127.0.0.1;Port=5432;Database=myDataBase;User Id=myUsername;Password=myPassword; // //// User ID=root;Password=myPassword;Host=localhost;Port=5432;Database=myDataBase; ////Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0; // // NpgsqlCommand command = new NpgsqlCommand("select * from test", con); // try { // NpgsqlDataReader dr = command.ExecuteReader(); // // Console.WriteLine(); // while (dr.Read()) { // var a = dr.GetValue(0).ToString(); // var b = dr.GetValues(new object[] {new int() , new string('l', 1)}); // var c = dr.GetValue(0).ToString(); // } // } catch (Exception ex) { // Console.WriteLine(ex); // } // con.Close(); TableEntity.Fields.Id, PredicateCondition.Equal, 1 var test = new TableEntity("test"); var results = test .Select() .Where(new[] { new FilterWhere(TableEntity.Fields.Id, PredicateCondition.Equal, 1), new FilterWhere(TableEntity.Fields.Id, PredicateCondition.Equal, 1) }) .GetData(); // foreach (var result in results) { // Console.WriteLine(result.Id + " " + result.Data); // } test.Id = 55765; test.Data = "saved"; test.Save(); results = test.Select().Where(TableEntity.Fields.Id, PredicateCondition.Equal, 55).GetData(); foreach (var result in results) { Console.WriteLine(result.Id + " " + result.Data); } Console.ReadKey(); }
//static void context_ReadingEntity(object sender, ReadingWritingEntityEventArgs args) //{ // TableEntity entity = args.Entity as TableEntity; // if (entity == null) // return; // // read each property, type and value in the payload // var properties = args.Entity.GetType().GetProperties(); // var q = from p in args.Data.Element(AtomNamespace + "content") // .Element(AstoriaMetadataNamespace + "properties") // .Elements() // where properties.All(pp => pp.Name != p.Name.LocalName) // select new // { // Name = p.Name.LocalName, // p.Value // }; // foreach (var dp in q) // entity[dp.Name] = dp.Value; //} public static void DeleteEntity(string account, string key, string tableName, string partitionKey, string rowKey) { CloudTableClient tableClient = Client.GetTableClient(account, key); CloudTable table = tableClient.GetTableReference(tableName); TableEntity entity = new TableEntity() { PartitionKey = partitionKey, RowKey = rowKey, ETag = "*" }; TableOperation delete = TableOperation.Delete(entity); table.Execute(delete); //TableServiceContext context = tableClient.GetDataServiceContext(); //context.AttachTo(table, entity, "*"); //context.DeleteObject(entity); //context.SaveChangesWithRetries(SaveChangesOptions.None); }
public Table(TableEntity table) : base(table) { Number = table.Number; Description = table.Description; }
public Table AddTable(int managerId, int tableNumber, string description) { if (!CheckHasUserRole(managerId, UserRole.Manager)) throw new SecurityException(String.Format("User id = {0} is not logged in or is no manager", managerId)); if (String.IsNullOrEmpty(description)) throw new ArgumentNullException("description"); TableEntity newTable = null; using (var db = new DataAccessProvider()) { var tableToAdd = new TableEntity() { Number = tableNumber, Description = description }; var tablesSameNumber = db.Tables.Where(t => t.Number.Equals(tableNumber)); if(tablesSameNumber != null && tablesSameNumber.Any()) foreach(TableEntity tableEntity in tablesSameNumber) if(tableEntity.Equals(tableToAdd)) { if (tableEntity.IsDeleted) tableEntity.IsDeleted = false; newTable = tableEntity; break; } if(newTable == null) newTable = db.Tables.Add(tableToAdd); db.SaveChanges(); } return new Table(newTable); }
private void CreateStorageAssociations(TableEntity entity) { foreach (var association in entity.Associations) { IEntity principalEntity; IEntity dependentEntity; bool isParentEntity; ResolveAssociationValues(association, out principalEntity, out dependentEntity, out isParentEntity); if (ExcludeAssociation(association) || !association.IsParentEntity || principalEntity is TableEnumEntity || dependentEntity is TableEnumEntity || _storageAssociations.Contains(association.AssociationKeyName)) continue; CreateStorageAssociationSet(association); CreateStorageAssociation(association); if (association.IsParentManyToMany()) { CreateStorageAssociationSet(association.IntermediaryAssociation); CreateStorageAssociation(association.IntermediaryAssociation); } } }
public static void InsertOrReplaceEntity( SqlString accountName, SqlString sharedKey, SqlBoolean useHTTPS, SqlString tableName, SqlString partitionKey, SqlString rowKey, SqlXml AttributeList, SqlString xmsclientrequestId) { ITPCfSQL.Azure.AzureTableService ats = new AzureTableService(accountName.Value, sharedKey.Value, useHTTPS.Value); ITPCfSQL.Azure.Table table = ats.GetTable(tableName.Value); ITPCfSQL.Azure.TableEntity te = new TableEntity(partitionKey.Value, rowKey.Value); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(AttributeList.Value); foreach (System.Xml.XmlNode nAttrib in doc.FirstChild.ChildNodes) { te.Attributes[nAttrib.Name] = nAttrib.InnerText; } table.InsertOrUpdate(te, xmsclientrequestId != null ? xmsclientrequestId.Value : null); }
private void CreateConceptualAssociations(TableEntity entity) { foreach (var association in entity.Associations) { IEntity principalEntity; IEntity dependentEntity; bool isParentEntity; string key; string toRole; string fromRole; ResolveConceptualAssociationValues(association, out principalEntity, out dependentEntity, out isParentEntity, out key, out toRole, out fromRole); if (ExcludeAssociation(association) || !isParentEntity || principalEntity is TableEnumEntity || dependentEntity is TableEnumEntity || _conceptualAssociations.Contains(key)) continue; CreateConceptualAssociationSet(association); CreateConceptualAssociation(association); } //<NavigationProperty Name="Products" Relationship="PetShopModel1.FK__Product__Categor__0CBAE877" FromRole="Category" ToRole="Product" /> var entityType = ConceptualSchema.EntityTypes.FirstOrDefault(e => ResolveEntityMappedName(entity.EntityKey(), entity.Name).Equals(e.Name, StringComparison.OrdinalIgnoreCase)); if (!entity.IsParentManyToMany() && entityType != null) { // Add new Associations. foreach (var association in entity.Associations) { IEntity principalEntity; IEntity dependentEntity; bool isParentEntity; string key; string toRole; string fromRole; ResolveConceptualAssociationValues(association, out principalEntity, out dependentEntity, out isParentEntity, out key, out toRole, out fromRole); if (principalEntity is TableEnumEntity || dependentEntity is TableEnumEntity) continue; CreateConceptualNavigationProperty(entityType, association); } } }