// TODO: Create Command interface public bool executeStatement(string strSql) { bool wasSuccessful = false; // TODO: Think how to track multiple tables/TableContexts // Note that the constructor will set up the table named // in the SELECT statement in _table. CommandParts updateParts = new CommandParts(_database, _table, strSql, CommandParts.COMMAND_TYPES.UPDATE); if (MainClass.bDebug) { Console.WriteLine("SELECT: " + updateParts.strSelect); Console.WriteLine("FROM: " + updateParts.strFrom); if (!string.IsNullOrEmpty(updateParts.strInnerJoinKludge)) { throw new Exception("Syntax error: INNER JOIN in an UPDATE statement is not supported: " + strSql); } Console.WriteLine("WHERE: " + updateParts.strWhere); // Note that WHEREs aren't applied to inner joined tables right now. Console.WriteLine("ORDER BY: " + updateParts.strOrderBy); } _table = _database.getTableByName(updateParts.strTableName); DataTable dtThrowAway = new DataTable(); WhereProcessor.ProcessRows(ref dtThrowAway, _table, updateParts); return(wasSuccessful); }
protected IEnumerable <Attachment> GetAttachmentHeaders() { if (!HasAttachments) { yield break; } var attachmentSet = new HashSet <string>(); foreach (var subNode in SubNodeHeaderDataDto) { if ((NodeValue)subNode.Key != NodeValue.AttachmentTable) { throw new Exception("expected node to be an attachment table"); } var attachmentTable = new TableContext(subNode.Value); var attachmentRows = attachmentTable.RowMatrix.Rows; foreach (var attachmentRow in attachmentRows) { var attachment = new Attachment(attachmentRow); yield return(attachment); } } }
public string AddUser(RegisteredUser user, int depId, int gid) { using (var db = new TableContext()) { try { var tempstatus = db.statuses.Find(2); var tempGender = db.Genders.Find(gid); var tempdep = db.departments.Find(depId); var temptype = db.Usertypes.Find(2); user.IsDeleted = false; user.Status = tempstatus; user.Department = tempdep; user.UserTypes = temptype; user.Gender = tempGender; db.Rusers.Add(user); db.SaveChanges(); return("User was added"); } catch (Exception ex) { return(ex.Message); } } }
public void TestActionWhenContextIsATableProcessesActions() { var action = new Mock<IAction>(MockBehavior.Strict); var items = new List<IValidationComparer> { new StartsWithComparer() }.AsReadOnly(); var actionRepository = new Mock<IActionRepository>(MockBehavior.Strict); actionRepository.Setup(a => a.GetComparisonTypes()).Returns(items); var tokenManager = new Mock<ITokenManager>(MockBehavior.Strict); tokenManager.Setup(t => t.GetToken("foo")).Returns("foo"); var preAction = new ValidationTablePreAction(actionRepository.Object, tokenManager.Object); var table = new ValidationTable(); table.AddValidation("My Field", "starts with", "foo"); var context = new TableContext(table); preAction.PerformPreAction(action.Object, context); var validation = table.Validations.First(); Assert.AreEqual("myfield", validation.FieldName); Assert.AreEqual("foo", validation.ComparisonValue); Assert.IsNotNull(validation.Comparer); Assert.IsInstanceOfType(validation.Comparer, typeof(StartsWithComparer)); action.VerifyAll(); actionRepository.VerifyAll(); tokenManager.VerifyAll(); }
public Recipients GetRecipients() { const ulong recipientsFlag = 1682; var recipients = new Recipients(); var exists = SubNodeDataDto.TryGetValue(recipientsFlag, out NodeDataDTO subNode); if (!exists) { return(recipients); } var recipientTable = new TableContext(subNode); foreach (var row in recipientTable.RowMatrix.Rows) { var recipient = new Recipient(row); switch (recipient.Type) { case Recipient.RecipientType.TO: recipients.To.Add(recipient); break; case Recipient.RecipientType.CC: recipients.CC.Add(recipient); break; case Recipient.RecipientType.BCC: recipients.BCC.Add(recipient); break; } } return(recipients); }
public MailFolder(ulong NID, List <string> path, PSTFile pst) { this._pst = pst; this.Path = path; var nid = NID; var pcNID = ((nid >> 5) << 5) | 0x02; this.PC = new PropertyContext(pcNID, pst); this.DisplayName = Encoding.Unicode.GetString(this.PC.Properties[0x3001].Data); this.Path = new List <string>(path); this.Path.Add(DisplayName); var heirachyNID = ((nid >> 5) << 5) | 0x0D; var contentsNID = ((nid >> 5) << 5) | 0x0E; var faiNID = ((nid >> 5) << 5) | 0x0F; this.HeirachyTC = new TableContext(heirachyNID, pst); this.SubFolders = new List <MailFolder>(); foreach (var row in this.HeirachyTC.ReverseRowIndex) { this.SubFolders.Add(new MailFolder(row.Value, this.Path, pst)); //var temp = row.Key; //var temp2 = row.Value; //this.SubFolderEntryIDs.Add(row.); } this.ContentsTC = new TableContext(contentsNID, pst); this.FaiTC = new TableContext(faiNID, pst); }
public string InsertAddress(Address addres, int id, int addtype, int subid) { try { using (var db = new TableContext()) { var person = db.Rusers.Where(s => s.RegisteredUserID == id).FirstOrDefault(); var type = db.addresstypes.Find(addtype); addres.Addresstypes = type; var sub = db.surbubs.Find(subid); addres.sub = sub; addres.RegisteredUsers = person; db.addresses.Add(addres); db.SaveChanges(); person.AddressID = addres.AddressID; db.Entry(person).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } return("address was added"); } catch (Exception ex) { return(ex.Message); } }
public void TestActionWhenContextIsATableButHasBadRuleProcessesActions() { var action = new Mock <IAction>(MockBehavior.Strict); var items = new List <IValidationComparer> { new StartsWithComparer(), new EqualsComparer() }.AsReadOnly(); var actionRepository = new Mock <IActionRepository>(MockBehavior.Strict); actionRepository.Setup(a => a.GetComparisonTypes()).Returns(items); var tokenManager = new Mock <ITokenManager>(MockBehavior.Strict); var preAction = new ValidationTablePreAction(actionRepository.Object, tokenManager.Object); var table = new ValidationTable(); table.AddValidation("My Field", "bad rule", "foo"); var context = new TableContext(table); try { preAction.PerformPreAction(action.Object, context); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(ElementExecuteException)); Assert.AreEqual("Vaidation Rule could not be found for rule name: bad rule", e.Message); } action.VerifyAll(); actionRepository.VerifyAll(); tokenManager.VerifyAll(); }
public ActionResult AddOrEdit(Teacher teacher) { try { if (teacher.ImageUpload != null) { string fileName = Path.GetFileNameWithoutExtension(teacher.ImageUpload.FileName); string extension = Path.GetExtension(teacher.ImageUpload.FileName); fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension; teacher.TecherImage = "~/Images/" + fileName; teacher.ImageUpload.SaveAs(Path.Combine(Server.MapPath("~/Images/"), fileName)); } using (TableContext db = new TableContext()) { if (teacher.TeacherID == 0) { db.Teachers.Add(teacher); db.SaveChanges(); } else { db.Entry(teacher).State = EntityState.Modified; db.SaveChanges(); } } return(Json(new { success = true, html = GlobalClass.RenderRazorViewToString(this, "ViewAll", GetAllTeacher()), message = "Submitted Successfully" }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet)); } }
IEnumerable <Teacher> GetAllTeacher() { using (TableContext db = new TableContext()) { return(db.Teachers.ToList <Teacher>()); } }
public void _parseStatement(string strSql) { int intTail = strSql.Length; int intIndexOf = -1; // TODO: Standardize on CurrentCultureIgnoreCase or ToLower. if (!strSql.ToLower().StartsWith("delete") || !strSql.ToLower().Contains("from")) { throw new Exception("Invalid DELETE statement"); } intIndexOf = strSql.IndexOf("WHERE", StringComparison.CurrentCultureIgnoreCase); if (-1 < intIndexOf) { this.strWhere = strSql.Substring(intIndexOf, intTail - intIndexOf); intTail = intIndexOf; } intIndexOf = strSql.IndexOf("FROM", StringComparison.CurrentCultureIgnoreCase); if (-1 < intIndexOf) { this.strFrom = strSql.Substring(intIndexOf, intTail - intIndexOf); this.strTableName = this.strFrom.Split()[1]; _tableContext = _database.getTableByName(this.strTableName); if (null == _tableContext) { throw new Exception("Table does not exist: " + this.strTableName); } intTail = intIndexOf; } this.strDelete = strSql.Substring(0, intTail); }
public static Table GetInformation(int id) { using (TableContext db = new TableContext()) { var answer = db.Table.Find(id); return(answer); } }
public UserRepository() { var connectionString = ConfigurationManager.AppSettings["AzureStorageConnectionString"]; //var storageAccount = CloudStorageAccount.Parse(connectionString); UserContext = new TableContext <User>(connectionString, "UserId"); InitIndexDefinitions(); }
public SelectSqlBuilder LeftOuterJoin(TableContext firstContext, TableContext secondContext, string name, string identityField) { _joinClauses.Add(string.Format("LEFT OUTER JOIN {0} AS {1} ON {2} = {3}", Escape(secondContext.Table.Name), Escape(secondContext.Alias), Column(firstContext, name), Column(secondContext, identityField) )); return this; }
public static void SaveInformation(string url, string body) { using (TableContext db = new TableContext()) { db.Table.Add(new Table { URL = url, Body = body }); db.SaveChanges(); } }
public ActionResult Index() { var db = new TableContext(); int userId = int.Parse(TempData["userId"].ToString()); var user = db.Users.Where(u => u.Id == userId).FirstOrDefault(); var userDTO = UserCommon.ConvertBOtoDTO(user); return(View(userDTO)); }
private static List <Comparison> _CreateWhereConditions(string strWhere, TableContext table) { List <Comparison> lstReturn = new List <Comparison>(); if (!string.IsNullOrWhiteSpace(strWhere)) { strWhere = strWhere.Substring(6); string[] astrClauses = strWhere.SplitSeeingSingleQuotesAndBackticks("AND", false).ToArray(); // TODO: Handle NOTs, duh. for (int i = 0; i < astrClauses.Length; i++) { Comparison comparison = null; string strClause = astrClauses[i].Trim(); if (MainClass.bDebug) { Console.WriteLine("Where clause #" + i + " " + strClause); } if (strClause.SplitSeeingSingleQuotesAndBackticks(" IN ", false).Count > 1) { CompoundComparison inClause = new CompoundComparison(GROUP_TYPE.OR); if (MainClass.bDebug) { Console.WriteLine("IN clause: " + strClause); } string strField = strClause.Substring(0, strClause.IndexOf(' ')); string strIn = strClause.Substring(strClause.IndexOf('(') + 1, strClause.LastIndexOf(')') - strClause.IndexOf('(') - 1); string[] astrInVals = strIn.Split(','); foreach (string strInVal in astrInVals) { string strFakeWhere = strField + " = " + strInVal; inClause.lstComparisons.Add(WhereProcessor._CreateComparison(strFakeWhere, table)); } lstReturn.Add(inClause); } else { comparison = WhereProcessor._CreateComparison(strClause, table); if (null != comparison) { lstReturn.Add(comparison); } else { Console.WriteLine("Uncaptured WHERE clause type: " + strClause); } } } } return(lstReturn); }
public void ProcessElement_TableCell_NotFoundTest() { var table = TableSimple.Build3x3(); _tableContext = new TableContext() { GridStateFactory = _instance.GridStateFactory }; _tableContext.AddTable(table, 10); Assert.IsFalse(_instance.ProcessElement(_elemState, new TableCell())); }
public string DeactivateUser(int id) { using (var db = new TableContext()) { var st = db.statuses.Find(2); var tempuser = db.Rusers.Where(s => s.RegisteredUserID == id).FirstOrDefault(); tempuser.Status = st; db.Entry(tempuser).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } return("User was Deactivated"); }
public string SoftDeleteUser(int id) { using (var db = new TableContext()) { var tempuser = db.Rusers.Where(s => s.RegisteredUserID == id).FirstOrDefault(); //tempuser.IsDeleted=true; tempuser.IsDeleted = true; db.Entry(tempuser).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } return("User was Deleted"); }
public string UpdateAddress(int id, Address upadd, int?subID, int?typeId) { Address tempaddress = new Address(); using (var db = new TableContext()) { var readdress = db.addresses.Find(id); tempaddress = readdress; try { if (!string.IsNullOrEmpty(upadd.UnitNumber)) { tempaddress.UnitNumber = upadd.UnitNumber; } if (upadd.StreetName != "") { tempaddress.StreetName = upadd.StreetName; } if (!string.IsNullOrEmpty(upadd.ComplexNumber)) { tempaddress.ComplexNumber = upadd.ComplexNumber; } if (typeId != null) { var type = db.addresstypes.Where(s => s.AddressTypeID == typeId).FirstOrDefault(); tempaddress.Addresstypes = type; } if (subID != null) { var sub = db.surbubs.Where(s => s.SurbubID == subID).FirstOrDefault(); tempaddress.sub = sub; } db.Entry(tempaddress).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return("address was updated"); } catch (Exception ex) { return(ex.Message); } } }
public void ProcessElement_TableRow_Test() { var table = TableSimple.Build3x3(); _tableContext = new TableContext() { GridStateFactory = _instance.GridStateFactory }; _tableContext.AddTable(table, 10); var row = table.ChildElements.First <TableRow>(); Assert.IsTrue(_instance.ProcessElement(_elemState, row)); }
public ActionResult AddOrEdit(int id = 0) { Teacher teacher = new Teacher(); if (id != 0) { using (TableContext db = new TableContext()) { teacher = db.Teachers.Where(x => x.TeacherID == id).FirstOrDefault <Teacher>(); } } return(View(teacher)); }
public ActionResult SignUp(UserDTO userDTO) { var db = new TableContext(); var user = UserCommon.ConvertDTOtoBO(userDTO); if (ModelState.IsValid) { TempData["submitMessage"] = "success"; db.Users.Add(user); db.SaveChanges(); } return(View()); }
public MailFolder(ulong NID, List <string> path, PSTFile pst) { _pst = pst; Path = path; var nid = NID; var pcNID = ((nid >> 5) << 5) | 0x02; PC = new PropertyContext(pcNID, pst); DisplayName = pst.Header.isUnicode ? Encoding.Unicode.GetString(PC.Properties[MessageProperty.DisplayName].Data) : Encoding.ASCII.GetString(PC.Properties[MessageProperty.DisplayName].Data); Path = new List <string>(path); Path.Add(DisplayName); var heirachyNID = ((nid >> 5) << 5) | 0x0D; var contentsNID = ((nid >> 5) << 5) | 0x0E; var faiNID = ((nid >> 5) << 5) | 0x0F; HierarchyTC = new TableContext(heirachyNID, pst); SubFolders = new List <MailFolder>(); foreach (var row in HierarchyTC.ReverseRowIndex) { SubFolders.Add(new MailFolder(row.Value, Path, pst)); //var temp = row.Key; //var temp2 = row.Value; //SubFolderEntryIDs.Add(row.); } ContentsTC = new TableContext(contentsNID, pst); FaiTC = new TableContext(faiNID, pst); Messages = new List <Message>(); OtherItems = new List <IPMItem>(); foreach (var row in ContentsTC.ReverseRowIndex) { var item = new IPMItem(_pst, row.Value); //if (item.MessageClass.StartsWith("IPM.Note")) //{ Messages.Add(new Message(row.Value, _pst)); //} //else //{ // OtherItems.Add(item); //} } }
/// <summary> /// Start the parse processing. /// </summary> /// <returns>Returns a list of parsed paragraph.</returns> public IList <OpenXmlCompositeElement> Parse(String html) { if (String.IsNullOrEmpty(html)) { return(new Paragraph[0]); } // ensure a body exists to avoid any errors when trying to access it if (mainPart.Document == null) { new Document(new Body()).Save(mainPart); } else if (mainPart.Document.Body == null) { mainPart.Document.Body = new Body(); } // Reset: elements = new List <OpenXmlElement>(); paragraphs = new List <OpenXmlCompositeElement>(); tables = new TableContext(); htmlStyles.Runs.Reset(); currentParagraph = null; // Start a new processing paragraphs.Add(currentParagraph = htmlStyles.Paragraph.NewParagraph()); if (htmlStyles.DefaultParagraphStyle != null) { currentParagraph.ParagraphProperties = new ParagraphProperties { ParagraphStyleId = new ParagraphStyleId { Val = htmlStyles.DefaultParagraphStyle } }; } HtmlEnumerator en = new HtmlEnumerator(html); ProcessHtmlChunks(en, null); if (elements.Count > 0) { this.currentParagraph.Append(elements); } // As the Parse method is public, to avoid changing the type of the return value, I use this proxy // that will allow me to call the recursive method RemoveEmptyParagraphs with no major changes, impacting the client. RemoveEmptyParagraphs(); return(paragraphs); }
private IElementProcessingState MockElemProcessingStateWithTableContext() { var tableContext = new TableContext() { GridStateFactory = _instance.GridStateFactory }; tableContext.AddTable(TableSimple.Build3x3(), 0); _fullCssData.AddRange(tableContext.GetCssData()); var elemState = new ElementProcessingState(); elemState.SetContext(tableContext); return(elemState); }
public AssociatedTableContext(ExpressionParser parser, TableContext parent, Association association) : base(parser, parent.SqlQuery) { var type = TypeHelper.GetMemberType(association.MemberAccessor.MemberInfo); var left = association.CanBeNull; var isList = false; if (TypeHelper.IsSameOrParent(typeof(IEnumerable), type)) { var etypes = TypeHelper.GetGenericArguments(type, typeof(IEnumerable)); type = etypes != null && etypes.Length > 0 ? etypes[0] : TypeHelper.GetListItemType(type); isList = true; } OriginalType = type; ObjectType = GetObjectType(); ObjectMapper = Parser.MappingSchema.GetObjectMapper(ObjectType); SqlTable = new SqlTable(parser.MappingSchema, ObjectType); var psrc = parent.SqlQuery.From[parent.SqlTable]; var join = left ? SqlTable.WeakLeftJoin() : isList?SqlTable.InnerJoin() : SqlTable.WeakInnerJoin(); _parentAssociation = parent; ParentAssociationJoin = join.JoinedTable; psrc.Joins.Add(join.JoinedTable); //Init(mappingSchema); for (var i = 0; i < association.ThisKey.Length; i++) { SqlField field1; SqlField field2; if (!parent.SqlTable.Fields.TryGetValue(association.ThisKey[i], out field1)) { throw new LinqException("Association key '{0}' not found for type '{1}.", association.ThisKey[i], parent.ObjectType); } if (!SqlTable.Fields.TryGetValue(association.OtherKey[i], out field2)) { throw new LinqException("Association key '{0}' not found for type '{1}.", association.OtherKey[i], ObjectType); } join.Field(field1).Equal.Field(field2); } }
private void BuildAssociationCondition(ExpressionBuilder builder, TableContext parent, AssociationDescriptor association, SqlSearchCondition condition) { for (var i = 0; i < association.ThisKey.Length; i++) { if (!parent.SqlTable.Fields.TryGetValue(association.ThisKey[i], out var field1)) { throw new LinqException("Association key '{0}' not found for type '{1}.", association.ThisKey[i], parent.ObjectType); } if (!SqlTable.Fields.TryGetValue(association.OtherKey[i], out var field2)) { throw new LinqException("Association key '{0}' not found for type '{1}.", association.OtherKey[i], ObjectType); } ISqlPredicate predicate = new SqlPredicate.ExprExpr( field1, SqlPredicate.Operator.Equal, field2); predicate = builder.Convert(parent, predicate); condition.Conditions.Add(new SqlCondition(false, predicate)); } if (ObjectType != OriginalType) { var predicate = Builder.MakeIsPredicate(this, OriginalType); if (predicate.GetType() != typeof(SqlPredicate.Expr)) { condition.Conditions.Add(new SqlCondition(false, predicate)); } } RegularConditionCount = condition.Conditions.Count; ExpressionPredicate = Association.GetPredicate(parent.ObjectType, ObjectType); if (ExpressionPredicate != null) { ExpressionPredicate = (LambdaExpression)Builder.ConvertExpressionTree(ExpressionPredicate); var expr = Builder.ConvertExpression(ExpressionPredicate.Body.Unwrap()); Builder.BuildSearchCondition( new ExpressionContext(parent.Parent, new IBuildContext[] { parent, this }, ExpressionPredicate), expr, condition.Conditions, false); } }
public AssociatedTableContext(ExpressionBuilder builder, TableContext parent, AssociationDescriptor association) : base(builder, parent.SelectQuery) { var type = association.MemberInfo.GetMemberType(); var left = association.CanBeNull; if (typeof(IEnumerable).IsSameOrParentOf(type)) { var etypes = type.GetGenericArguments(typeof(IEnumerable <>)); type = etypes != null && etypes.Length > 0 ? etypes[0] : type.GetListItemType(); IsList = true; } OriginalType = type; ObjectType = GetObjectType(); EntityDescriptor = Builder.MappingSchema.GetEntityDescriptor(ObjectType); SqlTable = new SqlTable(builder.MappingSchema, ObjectType); var psrc = parent.SelectQuery.From[parent.SqlTable]; var join = left ? SqlTable.WeakLeftJoin() : IsList?SqlTable.InnerJoin() : SqlTable.WeakInnerJoin(); Association = association; ParentAssociation = parent; ParentAssociationJoin = join.JoinedTable; psrc.Joins.Add(join.JoinedTable); for (var i = 0; i < association.ThisKey.Length; i++) { SqlField field1; SqlField field2; if (!parent.SqlTable.Fields.TryGetValue(association.ThisKey[i], out field1)) { throw new LinqException("Association key '{0}' not found for type '{1}.", association.ThisKey[i], parent.ObjectType); } if (!SqlTable.Fields.TryGetValue(association.OtherKey[i], out field2)) { throw new LinqException("Association key '{0}' not found for type '{1}.", association.OtherKey[i], ObjectType); } join.Field(field1).Equal.Field(field2); } Init(); }
protected override Expression BuildQuery(Type tableType, TableContext tableContext, ParameterExpression parentObject) { if (IsList == false) { return(base.BuildQuery(tableType, tableContext, parentObject)); } if (Common.Configuration.Linq.AllowMultipleQuery == false) { throw new LinqException("Multiple queries are not allowed. Set the 'LinqToDB.Common.Configuration.Linq.AllowMultipleQuery' flag to 'true' to allow multiple queries."); } var sqtype = typeof(SubQueryHelper <>).MakeGenericType(tableType); var helper = (ISubQueryHelper)Activator.CreateInstance(sqtype); return(helper.GetSubquery(Builder, this, parentObject)); }
// TODO: Create Command interface public void executeStatement(string strSql) { DeleteParts deleteParts = new DeleteParts(_database, strSql); if (MainClass.bDebug) { Console.WriteLine("DELETE: " + deleteParts.strDelete); Console.WriteLine("FROM: " + deleteParts.strFrom); Console.WriteLine("WHERE: " + deleteParts.strWhere); } _table = _database.getTableByName(deleteParts.strTableName); List <Comparison> lstWhereConditions = _createWhereConditions(deleteParts.strWhere); _deleteRows(lstWhereConditions); }
protected static string Column(TableContext table, string column) { return string.Format("{0}.{1}", Escape(table.Alias), Escape(column)); }
public SelectSqlBuilder SelectAll(TableContext context) { _selectClauses.Add(string.Format("{0}.*", Escape(context.Alias))); return this; }
public SelectSqlBuilder(TableContext context) { _fromClause = "FROM " + Escape(context.Table.Name) + " AS " + Escape(context.Alias); }
public DeleteSqlBuilder(TableContext mainTableContext) { _deleteClause = string.Format("DELETE FROM {1} FROM {0} AS {1}", Escape(mainTableContext.Table.Name), Escape(mainTableContext.Alias)); }
private static void DeleteRdfMetadata(string metadataSet, string entitySet, DataLoaderParams parameters) { var context = new TableContext(s_account.TableEndpoint.ToString(), s_account.Credentials, parameters) { RetryPolicy = RetryPolicies.RetryExponential(RetryPolicies.DefaultClientRetryCount, RetryPolicies.DefaultClientBackoff) }; string query = string.Format(s_metadataRdfQueryTemplate, metadataSet, entitySet); List<TableEntity> results = context.Execute<TableEntity>(new Uri(query, UriKind.Relative)).ToList(); if (results.Count > 0) { foreach (TableEntity i in results) { context.DeleteObject(i); context.SaveChanges(); } } }
private static void DeleteMetadata(string metadataSet, string entitySet, string entityKind, DataLoaderParams parameters) { var context = new TableContext(s_account.TableEndpoint.ToString(), s_account.Credentials, parameters) { RetryPolicy = RetryPolicies.RetryExponential(RetryPolicies.DefaultClientRetryCount, RetryPolicies.DefaultClientBackoff) }; string query = string.Format(s_metadataEntityQueryTemplate, metadataSet, entitySet, entityKind); List<TableEntity> results = context.Execute<TableEntity>(new Uri(query, UriKind.Relative)).ToList(); if (results.Count == 1) { context.DeleteObject(results.First()); context.SaveChanges(); } else if (results.Count > 1) { throw new DuplicateEntityException(query); } }
public string Set(TableContext mainTableContext, string column) { var parm = GetNextParameter(); _sets.Add(GetEquality(mainTableContext, column, parm)); return parm; }
public string GetEquality(TableContext table, string column, string operand) { return string.Format("{0} = {1}", Column(table, column), operand); }
public string GetEquality(TableContext table, string column, TableContext table2, string column2) { return GetEquality(table, column, Column(table2, column2)); }
private static void CheckAndUpdateMetadataLastUpdateDate(string metadataSet, string entitySet, string entityKind, DateTime lastUpdateDate, DataLoaderParams Params) { var context = new TableContext(s_account.TableEndpoint.ToString(), s_account.Credentials, Params) { RetryPolicy = RetryPolicies.RetryExponential(RetryPolicies.DefaultClientRetryCount, RetryPolicies.DefaultClientBackoff) }; string query = string.Format(s_metadataEntityQueryTemplate, metadataSet, entitySet, entityKind); List<TableEntity> results = context.Execute<TableEntity>(new Uri(query, UriKind.Relative)).ToList(); if (results.Count == 1) { DateTime oldLastUpdateDate = new TableMetadataEntity(results[0]).LastUpdateDate; if (oldLastUpdateDate > lastUpdateDate) throw new MetadataOutdatedException(oldLastUpdateDate, lastUpdateDate); results[0].UpdateProperty(DataLoaderConstants.PropNameLastUpdateDate, lastUpdateDate); context.UpdateObject(results[0]); context.SaveChanges(); } else if (results.Count > 1) { throw new DuplicateEntityException(query); } }
private static void CheckMetadataChanges(string metadataSet, string entitySet, string entityKind, Entity entity, DataLoaderParams Params, MetadataKind metadataKind) { var context = new TableContext(s_account.TableEndpoint.ToString(), s_account.Credentials, Params) { RetryPolicy = RetryPolicies.RetryExponential(RetryPolicies.DefaultClientRetryCount, RetryPolicies.DefaultClientBackoff) }; string query = string.Format(s_metadataEntityQueryTemplate, metadataSet, entitySet, entityKind); List<TableEntity> results = context.Execute<TableEntity>(new Uri(query, UriKind.Relative)).ToList(); if (results.Count == 1) { var exceprionColumns = new[] { DataLoaderConstants.PropNameEntityId, DataLoaderConstants.PropNameLastUpdateDate }; string differences = results[0].FindDifferences(entity, exceprionColumns); if (differences != null) throw new MetadataChangedException(entitySet, differences); } else if (results.Count > 1) { throw new DuplicateEntityException(query); } else if (results.Count == 0) { throw new MetadataNotFoundException(entitySet, metadataKind); } }
private TableEntity LoadEntity(TableContext context, string entitySetName, string rowKeyColumn, string rowKeyValue, object origianlRowKeyValue, string parKeyColumn, string parKeyValue, object origianlParKeyValue) { // For string values add '' string rk = GetValueForQuery(rowKeyValue, origianlRowKeyValue); string pk = GetValueForQuery(parKeyValue, origianlParKeyValue); if (rowKeyColumn == "New.Guid") rowKeyColumn = "RowKey"; if (parKeyColumn == "New.Guid") parKeyColumn = "PartitionKey"; // columns should be in lower case string query = string.Format(S_ENTITY_QUERY_TEMPLATE, entitySetName, rowKeyColumn.ToLower(), rk, parKeyColumn.ToLower(), pk); List<TableEntity> results = context.Execute<TableEntity>(new Uri(query, UriKind.Relative)).ToList(); if (results.Count == 0) { return null; } if (results.Count > 1) { throw new DuplicateEntityException(query); } return results[0]; }
public UpdateSqlBuilder(TableContext mainTableContext) { string alias = Escape(mainTableContext.Alias); _updateClause = string.Format("UPDATE {0} SET", alias); _fromClause = string.Format(" FROM {0} AS {1}", Escape(mainTableContext.Table.Name), alias); }
/// <summary> /// Start the parse processing. /// </summary> /// <returns>Returns a list of parsed paragraph.</returns> public IList<OpenXmlCompositeElement> Parse(String html) { if (String.IsNullOrEmpty(html)) return new Paragraph[0]; // Reset: elements = new List<OpenXmlElement>(); paragraphs = new List<OpenXmlCompositeElement>(); tables = new TableContext(); htmlStyles.Runs.Reset(); currentParagraph = null; // Start a new processing paragraphs.Add(currentParagraph = htmlStyles.Paragraph.NewParagraph()); if (htmlStyles.DefaultParagraphStyle != null) { currentParagraph.Append(new ParagraphProperties( new ParagraphStyleId { Val = htmlStyles.DefaultParagraphStyle } )); } HtmlEnumerator en = new HtmlEnumerator(html); ProcessHtmlChunks(en, null); if (elements.Count > 0) this.currentParagraph.Append(elements); // As the Parse method is public, to avoid changing the type of the return value, I use this proxy // that will allow me to call the recursive method RemoveEmptyParagraphs with no major changes, impacting the client. RemoveEmptyParagraphs(); return paragraphs; }
private void StoreEntity(string entitySetName, string parKeyPropName, string rowKeyPropName, Entity entity) { var account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["DataConnectionString"]); var context = new TableContext(account.TableEndpoint.ToString(), account.Credentials, _parameters) { RetryPolicy = RetryPolicies.RetryExponential(5, new TimeSpan(0, 0, 1)) }; var kmlSnippet = (string)entity[DataLoaderConstants.PropNameKmlSnippet]; if (kmlSnippet != null && kmlSnippet.Length > 32 * 1024) { string blobName = Guid.NewGuid().ToString(); string containerName = entitySetName.ToLower(); StoreKmlSnippetAsBlob(containerName, blobName, kmlSnippet); entity[DataLoaderConstants.PropNameKmlSnippet] = string.Format(DataLoaderConstants.KmlSnippetReference, containerName, blobName); } var kmlCoords = (string)entity[DataLoaderConstants.PropNameKmlCoords]; if (kmlCoords != null && kmlCoords.Length > 32 * 1024) { string blobName = Guid.NewGuid().ToString(); string containerName = entitySetName.ToLower(); StoreKmlSnippetAsBlob(containerName, blobName, kmlCoords); entity[DataLoaderConstants.PropNameKmlCoords] = string.Format(DataLoaderConstants.KmlSnippetReference, containerName, blobName); } TableEntity tableEntity = null; bool isUpdate = false; if (_parameters != null) { string parKey; object pk = entity[parKeyPropName]; if (string.IsNullOrEmpty(entity.Number)) { parKey = (pk != null) ? ConvertToProperPartitionKey(ConvertValueToString(pk)) : entity.Id.ToString(); } else { parKey = entity.Number; } string rowKey = null; object rk = entity[rowKeyPropName]; if (rowKeyPropName.ToLower() == DataLoaderConstants.ValueUniqueAutoGen) { rowKey = Guid.NewGuid().ToString(); } else { rowKey = (rk != null) ? ConvertValueToString(entity[rowKeyPropName]) : Guid.NewGuid().ToString(); } //try to load entity from storage if (_overwriteMode == TableOverwriteMode.Add || _overwriteMode == TableOverwriteMode.Update) { tableEntity = LoadEntity(context, entitySetName, rowKeyPropName, rowKey, rk, parKeyPropName, parKey, pk); if (tableEntity != null && _overwriteMode == TableOverwriteMode.Add) throw new EntityAlreadyExistsException(entitySetName, rowKeyPropName, rowKey, parKeyPropName, parKey); if (tableEntity != null) { tableEntity.UpdateEntity(entity); isUpdate = true; } } //if not found, create new if (tableEntity == null) tableEntity = new TableEntity(entity, parKey, rowKey); } else { tableEntity = new TableEntity(entity); } if (!isUpdate) context.AddObject(entitySetName, tableEntity); else context.UpdateObject(tableEntity); try { context.SaveChanges(); } catch (StorageClientException e) { if (e.ErrorCode == StorageErrorCode.ResourceAlreadyExists && e.StatusCode == HttpStatusCode.Conflict) { throw new DuplicateEntityException(tableEntity.ToString(), e); } } catch (DataServiceRequestException e) { if (e.InnerException != null && ((DataServiceClientException)e.InnerException).StatusCode == (int)HttpStatusCode.Conflict) { throw new DuplicateEntityException(tableEntity.ToString(), e); } } }