/* * (non-Javadoc) * * @see * com.itextpdf.tool.xml.ITagProcessor#content(com.itextpdf.tool.xml.Tag, * java.util.List, com.itextpdf.text.Document, java.lang.String) */ public override IList<IElement> Content(IWorkerContext ctx, Tag tag, String content) { List<Chunk> sanitizedChunks = HTMLUtils.Sanitize(content, false); List<IElement> l = new List<IElement>(1); foreach (Chunk sanitized in sanitizedChunks) { HtmlPipelineContext myctx; try { myctx = GetHtmlPipelineContext(ctx); } catch (NoCustomContextException e) { throw new RuntimeWorkerException(e); } if (tag.CSS.ContainsKey(CSS.Property.TAB_INTERVAL)) { TabbedChunk tabbedChunk = new TabbedChunk(sanitized.Content); if (null != GetLastChild(tag) && GetLastChild(tag).CSS.ContainsKey(CSS.Property.XFA_TAB_COUNT)) { tabbedChunk.TabCount = int.Parse(GetLastChild(tag).CSS[CSS.Property.XFA_TAB_COUNT]); } l.Add(GetCssAppliers().Apply(tabbedChunk, tag,myctx)); } else if (null != GetLastChild(tag) && GetLastChild(tag).CSS.ContainsKey(CSS.Property.XFA_TAB_COUNT)) { TabbedChunk tabbedChunk = new TabbedChunk(sanitized.Content); tabbedChunk.TabCount = int.Parse(GetLastChild(tag).CSS[CSS.Property.XFA_TAB_COUNT]); l.Add(GetCssAppliers().Apply(tabbedChunk, tag, myctx)); } else { l.Add(GetCssAppliers().Apply(sanitized, tag, myctx)); } } return l; }
/** * Calls each method in this class and returns an aggregated list of selectors. * @param t the tag * @return set of selectors */ public IDictionary<String,object> CreateAllSelectors(Tag t) { IDictionary<String,object> set = new Dictionary<String,object>(); CssUtils.MapPutAll(set, CreateTagSelectors(t)); CssUtils.MapPutAll(set, CreateClassSelectors(t)); CssUtils.MapPutAll(set, CreateIdSelector(t)); return set; }
/// <summary> /// /// </summary> /// <param name="data"> /// A <see cref="object"/> /// </param> public override void Execute(Tag data = null) { if (data != null && data.LocalName != "proceed") return; ProtocolState.Socket.StartSecure(); ProtocolState.State = new ConnectedState(); ProtocolState.State.Execute(); }
/** * Creates selectors for a given tag. * @param t the tag to create selectors for. * @return all selectors for the given tag. */ public IDictionary<String,object> CreateTagSelectors(Tag t) { IDictionary<String,object> selectors = new Dictionary<String,object>(); selectors[t.Name] = null;; if (null != t.Parent) { Tag parent = t.Parent; StringBuilder b = new StringBuilder(t.Name); StringBuilder bStripped = new StringBuilder(t.Name); StringBuilder bElem = new StringBuilder(t.Name); StringBuilder bChild = new StringBuilder(t.Name); StringBuilder bChildSpaced = new StringBuilder(t.Name); Tag child = t; while (null != parent) { if (parent.Children.IndexOf(child) == 0) { bChild.Insert(0, '+').Insert(0, parent.Name); bChildSpaced.Insert(0, " + ").Insert(0, parent.Name); selectors[bChild.ToString()] = null; selectors[bChildSpaced.ToString()] = null; } b.Insert(0, " > ").Insert(0, parent.Name); selectors[b.ToString()] = null;; bStripped.Insert(0, ">").Insert(0, parent.Name); selectors[bStripped.ToString()] = null;; bElem.Insert(0, ' ').Insert(0, parent.Name); selectors[bElem.ToString()] = null; child = parent; parent = parent.Parent; } } return selectors; }
public float? GetHeight(Tag tag, float pageHeight) { float? height = null; String heightValue = null; if (tag.CSS.TryGetValue(HTML.Attribute.HEIGHT, out heightValue) || tag.Attributes.TryGetValue(HTML.Attribute.HEIGHT, out heightValue)) { if (utils.IsNumericValue(heightValue) || utils.IsMetricValue(heightValue)) { height = utils.ParsePxInCmMmPcToPt(heightValue); } else if (utils.IsRelativeValue(heightValue)) { Tag ancestor = tag; float? firstAncestorsHeight = 0; while (firstAncestorsHeight == 0 && ancestor.Parent != null) { ancestor = ancestor.Parent; firstAncestorsHeight = GetHeight(ancestor, pageHeight); } if (firstAncestorsHeight == 0) { height = utils.ParseRelativeValue(heightValue, pageHeight); } else if (firstAncestorsHeight != null) { height = utils.ParseRelativeValue(heightValue, firstAncestorsHeight.Value); } } } return height; }
/// <summary> /// Executes the disconnect command by sending the closing stream tag and closing the socket. /// </summary> /// <param name="data"> /// No <see cref="Tag"/> needed so we pass null. /// </param> public override void Execute(Tag data = null) { if (ProtocolState.Socket.Connected) { ProtocolState.Socket.Write("</stream:stream>"); } }
public void TestTag() { Tag tag = new Tag(); tag.Initialize("tag", null, null); Assert.AreEqual("tag", tag.Name); Assert.AreEqual(string.Empty, tag.Render(new Context())); }
public BasicHtml AddMetaDescription( params string [] values ) { foreach( var value in values ) { Head.InsertChildAfter( lastMeta, lastMeta = Meta.NewDescription( value ) ); } return this; }
/// <summary> /// Makes a layout from a layout guess. /// </summary> /// <param name="layout">The layout guess.</param> /// <param name="name">The name of the final layout.</param> /// <param name="groupTag">The group tag of the final layout. Can be <c>null</c>.</param> /// <returns></returns> public static TagLayout MakeLayout(TagLayoutGuess layout, string name, Tag groupTag) { var result = new TagLayout(name, layout.Size, groupTag); var finalizer = new LayoutGuessFinalizer(result, 0); finalizer.ProcessLayout(layout); return result; }
public void VerifyFontsizeTranslation() { AbstractTagProcessor a = new CustomTagProcessor(); Tag tag = new Tag("dummy"); tag.CSS["font-size"] = "16px"; a.StartElement(null, tag); Assert.AreEqual("12pt", tag.CSS["font-size"]); }
public void OnTagDeleted(Tag tag) { if (TagDeleted != null) { TagDeleted(new SingleItemEventArgs<Tag>(tag)); } }
public void VerifyEnd() { AbstractTagProcessor a = new CustomTagProcessor(); Tag tag = new Tag("dummy"); tag.CSS["page-break-after"] = "always"; IList<IElement> end = a.EndElement(null, tag, new List<IElement>()); Assert.AreEqual(Chunk.NEXTPAGE, end[0]); }
public void VerifyStart() { AbstractTagProcessor a = new CustomTagProcessor(); Tag tag = new Tag("dummy"); tag.CSS["page-break-before"] = "always"; IList<IElement> end = a.StartElement(null, tag); Assert.AreEqual(Chunk.NEXTPAGE, end[0]); }
/* (non-Javadoc) * @see com.itextpdf.tool.xml.css.CssApplier#apply(com.itextpdf.text.Element, com.itextpdf.tool.xml.Tag) */ virtual public LineSeparator Apply(LineSeparator ls, Tag t, IPageSizeContainable psc) { float lineWidth = 1; IDictionary<String, String> css = t.CSS; if (css.ContainsKey(CSS.Property.HEIGHT)) { lineWidth = CssUtils.GetInstance().ParsePxInCmMmPcToPt(css[CSS.Property.HEIGHT]); } ls.LineWidth = lineWidth; BaseColor lineColor = BaseColor.BLACK; if (css.ContainsKey(CSS.Property.COLOR)) { lineColor = HtmlUtilities.DecodeColor(css[CSS.Property.COLOR]); } else if (css.ContainsKey(CSS.Property.BACKGROUND_COLOR)) { lineColor = HtmlUtilities.DecodeColor(css[CSS.Property.BACKGROUND_COLOR]); } ls.LineColor = lineColor; float percentage = 100; String widthStr; css.TryGetValue(CSS.Property.WIDTH, out widthStr); if (widthStr != null) { if (widthStr.Contains("%")) { percentage = float.Parse(widthStr.Replace("%", ""), CultureInfo.InvariantCulture); } else { percentage = (CssUtils.GetInstance().ParsePxInCmMmPcToPt(widthStr)/psc.PageSize.Width)*100; } } ls.Percentage = percentage; ls.Offset = 9; return ls; }
public override string Process(Tag tag) { if (tag == null) return ""; float size = 0.0f; bool do_not_process = false; if (tag.Attributes.ContainsKey("")) { try { size = float.Parse(tag.Attributes[""]); } catch (System.FormatException) { do_not_process = true; } } else { do_not_process = true; } if (size == 0.0) { do_not_process = true; } if (do_not_process == true) { return tag.Content; } else { return "<span style=\"font-size:" + size + "pt;\">" + tag.Content + "</span>"; } }
/* * (non-Javadoc) * * @see com.itextpdf.tool.xml.ITagProcessor#startElement(com.itextpdf.tool.xml.Tag) */ public override IList<IElement> Start(IWorkerContext ctx, Tag tag) { String enc; tag.Attributes.TryGetValue("encoding", out enc); if (null != enc) { try { Encoding encd = null; try { encd = Encoding.GetEncoding(enc); } catch (ArgumentException) { } if (encd != null) { GetHtmlPipelineContext(ctx).CharSet(encd); if (LOGGER.IsLogging(Level.DEBUG)) { LOGGER.Debug( String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.META_CC), enc)); } } else { if (LOGGER.IsLogging(Level.DEBUG)) { LOGGER.Debug( String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.META_404), GetHtmlPipelineContext(ctx) .CharSet() == null ? "" : GetHtmlPipelineContext(ctx).CharSet().WebName)); } } } catch (NoCustomContextException) { throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT)); } } return new List<IElement>(0); }
/* (non-Javadoc) * @see com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document) */ public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent) { TableRowElement row = null; IList<IElement> l = new List<IElement>(1); if (Util.EqualsIgnoreCase(tag.Parent.Name, HTML.Tag.THEAD)) { row = new TableRowElement(currentContent, TableRowElement.Place.HEADER); } else if (Util.EqualsIgnoreCase(tag.Parent.Name, HTML.Tag.TBODY)) { row = new TableRowElement(currentContent, TableRowElement.Place.BODY); } else if (Util.EqualsIgnoreCase(tag.Parent.Name, HTML.Tag.TFOOT)) { row = new TableRowElement(currentContent, TableRowElement.Place.FOOTER); } else { row = new TableRowElement(currentContent, TableRowElement.Place.BODY); } int direction = GetRunDirection(tag); if (direction != PdfWriter.RUN_DIRECTION_DEFAULT) { foreach (HtmlCell cell in row.Content) { if (cell.RunDirection == PdfWriter.RUN_DIRECTION_DEFAULT) { cell.RunDirection = direction; } } } l.Add(row); return l; }
/** * Tries to calculate a width from a tag and it's ancestors. * @param tag the tag to use * @param roottags the root tags, * @param pagewidth the page width * @return the width */ public float GetWidth(Tag tag, IList<String> roottags, float pagewidth){ float width = 0; String widthValue; tag.CSS.TryGetValue(HTML.Attribute.WIDTH, out widthValue); if (widthValue == null) { tag.Attributes.TryGetValue(HTML.Attribute.WIDTH, out widthValue); } if (widthValue != null) { if (utils.IsNumericValue(widthValue) || utils.IsMetricValue(widthValue)) { width = utils.ParsePxInCmMmPcToPt(widthValue); } else if (utils.IsRelativeValue(widthValue)) { Tag ancestor = tag; float firstAncestorsWidth = 0; while (firstAncestorsWidth == 0 && ancestor.Parent != null) { ancestor = ancestor.Parent; firstAncestorsWidth = GetWidth(ancestor, roottags, pagewidth); } if (firstAncestorsWidth == 0) { width = utils.ParseRelativeValue(widthValue, pagewidth); } else { width = utils.ParseRelativeValue(widthValue, firstAncestorsWidth); } } } else if (roottags.Contains(tag.Name)){ width = pagewidth; } return width; }
private void CreateButton_Click(object sender, RoutedEventArgs e) { (Application.Current.RootVisual as MainPage).ClearStatus(); Tag task = new Tag() { Label = txtNewTag.Text.Trim() }; TaskrAdminClient proxy = new TaskrAdminClient( new SaaSGridSilverlightCustomBinding(new SaaSGridContextInspector()), new EndpointAddress(App.Current.Host.InitParams["taskrAdminAddress"]) ); proxy.SaveTagCompleted += (object s, SaveTagCompletedEventArgs args) => { if (null == args.Error) { BindTagList(); (Application.Current.RootVisual as MainPage).SetStatus("Tag saved successfully.", MainPage.MessageStatus.Success); } else { (Application.Current.RootVisual as MainPage).SetStatus(args.Error.Message, MainPage.MessageStatus.Error); } }; proxy.SaveTagAsync(task); }
public static Tag LoadFromStream(Stream stream) { BinaryReader binaryReader = new BinaryReader(stream); Tag tag = new Tag(); tag.ID = binaryReader.ReadByte(); byte b; uint size; b = binaryReader.ReadByte(); if (b < 0x80) { size = b; } else if (b == 0xFF) { size = binaryReader.ReadUInt32(); } else { size = ((uint)b & 0x7F) << 8; b = binaryReader.ReadByte(); size |= b; } tag.Data = binaryReader.ReadBytes((int)size); return tag; }
/* (non-Javadoc) * @see com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document) */ public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent) { List<IElement> l = new List<IElement>(1); if (currentContent.Count > 0) { IList<IElement> currentContentToParagraph = CurrentContentToParagraph(currentContent, true, true, tag, ctx); foreach (IElement p in currentContentToParagraph) { ((Paragraph) p).Role = (getHeaderRole(GetLevel(tag))); } ParentTreeUtil pt = new ParentTreeUtil(); try { HtmlPipelineContext context = GetHtmlPipelineContext(ctx); bool oldBookmark = context.AutoBookmark(); if (pt.GetParentTree(tag).Contains(HTML.Tag.TD)) context.AutoBookmark(false); if (context.AutoBookmark()) { Paragraph title = new Paragraph(); foreach (IElement w in currentContentToParagraph) { title.Add(w); } l.Add(new WriteH(context, tag, this, title)); } context.AutoBookmark(oldBookmark); } catch (NoCustomContextException e) { if (LOGGER.IsLogging(Level.ERROR)) { LOGGER.Error(LocaleMessages.GetInstance().GetMessage(LocaleMessages.HEADER_BM_DISABLED), e); } } l.AddRange(currentContentToParagraph); } return l; }
public void AddsNamespaceToOutput(Namespaces namespaces, Tag tag) { sut.UseNamespaces(namespaces); sut.WriteStartTagFor(tag); Assert.Equal($"<{tag} {namespaces}>", sut.ToString()); }
public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent) { if (currentContent.Count > 0) { IDictionary<string, string> attributes = tag.Attributes; var retval = base.End(ctx, tag, currentContent); foreach (PdfPTable table in retval.OfType<PdfPTable>()) { if (attributes.ContainsKey("summary") && attributes.ContainsKey("caption")) { table.SetAccessibleAttribute(PdfName.SUMMARY, new PdfString(attributes["summary"].ToString())); table.SetAccessibleAttribute(PdfName.CAPTION, new PdfString(attributes["caption"].ToString())); table.KeepRowsTogether(0); } else { throw new Exception("Table is missing attributes. Summary and Caption must be available."); } } return retval; } return new List<IElement>(); }
/// <summary> /// Creates a tag layout with a name, a size in bytes, and a group tag. /// </summary> /// <param name="name">The name of the layout.</param> /// <param name="size">The size of the layout.</param> /// <param name="groupTag">The group tag.</param> public TagLayout(string name, uint size, Tag groupTag) { Name = name; Size = size; GroupTag = groupTag; Fields = _fields.AsReadOnly(); }
public override void Load() { Health = Data["Health"]; AttackTime = Data["AttackTime"]; DeathTime = Data["DeathTime"]; HurtTime = Data["HurtTime"]; }
public void SomeTests() { Tag t1 = new Tag (null, 1, "tag1"); Tag t2 = new Tag (null, 2, "tag2"); Tag t3 = new Tag (null, 3, "tag3"); Tag t4 = new Tag (null, 4, "tag4"); Tag t5 = new Tag (null, 5, "tag5"); TagTerm tt1 = new TagTerm (t1); TagTerm tt2 = new TagTerm (t2); TagTerm tt3 = new TagTerm (t3); TagTerm tt4 = new TagTerm (t4); TagTerm tt5 = new TagTerm (t5); object [] tests = { " (photos.id IN (SELECT photo_id FROM photo_tags WHERE tag_id = 1)) ", tt1, " (photos.id IN (SELECT photo_id FROM photo_tags WHERE tag_id IN (2, 3))) ", new OrTerm (tt2, tt3), " (photos.id IN (SELECT photo_id FROM photo_tags WHERE tag_id IN (3, 4, 5))) ", new OrTerm (tt3, tt4, tt5), }; for (int i=0; i < tests.Length; i+=2) { //System.Console.WriteLine ((tests[i+1] as LogicalTerm).SqlClause ()); //System.Console.WriteLine (tests[i]); Assert.AreEqual (tests[i] as string, (tests[i+1] as LogicalTerm).SqlClause ()); } }
public static GameObject[] FindGameObjectsWithTags(Tag[] searchTags) { List<GameObject> searchResult = new List<GameObject> (); foreach (MultiTags taggedObject in taggedObjects) { bool tagsFound = true; foreach(Tag searchTag in searchTags) { bool tagFound = false; foreach(Tag objectTag in taggedObject.tags) { if(objectTag == searchTag) { tagFound = true; break; } } if (!tagFound) { tagsFound = false; break; } } if (tagsFound) { searchResult.Add(taggedObject.gameObject); } } return searchResult.ToArray(); }
virtual public void SetUp() { parent = new Tag("body"); parent.CSS[CSS.Property.FONT_FAMILY] = "Helvetica"; parent.CSS[CSS.Property.FONT_SIZE] = "12pt"; first = new Tag(null); first.CSS[CSS.Property.FONT_FAMILY] = "Helvetica"; first.CSS[CSS.Property.FONT_SIZE] = "12pt"; second = new Tag(null); second.CSS[CSS.Property.FONT_FAMILY] = "Helvetica"; second.CSS[CSS.Property.FONT_SIZE] = "12pt"; child = new Tag(null); child.CSS[CSS.Property.FONT_FAMILY] = "Helvetica"; child.CSS[CSS.Property.FONT_SIZE] = "12pt"; parent.AddChild(first); first.Parent = parent; second.Parent = parent; first.AddChild(child); second.AddChild(child); parent.CSS[CSS.Property.FONT_SIZE] = fst.TranslateFontSize(parent) + "pt"; first.CSS[CSS.Property.FONT_SIZE] = fst.TranslateFontSize(first) + "pt"; first.CSS[CSS.Property.TEXT_ALIGN] = CSS.Value.LEFT; second.CSS[CSS.Property.FONT_SIZE] = fst.TranslateFontSize(second) + "pt"; child.CSS[CSS.Property.FONT_SIZE] = fst.TranslateFontSize(child) + "pt"; firstPara = new Paragraph(new Chunk("default text for chunk creation")); secondPara = new Paragraph(new Chunk("default text for chunk creation")); configuration = new HtmlPipelineContext(null); applier.Apply(firstPara, first, configuration); }
public static IEnumerable<News> Tag(this IEnumerable<News> news, Tag tag) { Assertion.NotNull(news); Assertion.NotNull(tag); return news.Where(it => it != null && it.Tags.Contains(tag)); }
public Face (uint id, Gdk.Rectangle r) : base (id) { rect = r; photo_id = 0; tag_id = 0; tag = null; }
public async Task DeleteTagAsync(Tag tag) { _lexDbContext.Tags.Attach(tag); _lexDbContext.Tags.Remove(tag); await _lexDbContext.SaveChangesAsync(); }
public virtual TResult Click <TResult>() where TResult : IBlock { Tag.Click(); return(this.FindRelated <TResult>()); }
private void button2_Click(object sender, EventArgs e) { var allItems = this.groupBox1.Controls.OfType <Control>().ToArray(); foreach (var le in allItems.OfType <TextBox>()) { Plugin.Instance.PlayerInfos[int.Parse(le.Tag.ToString())].Name = le.Text.Trim(); } foreach (var le in allItems.OfType <ComboBox>()) { Plugin.Instance.PlayerInfos[int.Parse(le.Tag.ToString())].FirstPos = (A12Position)le.SelectedIndex; } Plugin.Instance.MyIndex = int.Parse(allItems.First(l => (l is RadioButton rb) && rb.Checked).Tag.ToString()); Plugin.DebugPlayerInfo(); this.button2.Enabled = false; Settings.Default.Save(); }
public void GetProductsInTag() { Tag t = tagDB.Get("Safirglas"); Assert.AreEqual(t.Products.Count, 2); }
public void GetTagFailIsNull() { Tag t = tagDB.Get("Hvid"); Assert.IsNull(t.Name); }
public async Task UpdateTagAsync(Tag tag) { _lexDbContext.Tags.Update(tag); await _lexDbContext.SaveChangesAsync(); }
public async Task EditTagAsync(Tag tag, string newContent) { tag.Content = newContent; tag.Revisions++; await UpdateTagAsync(tag); }
public async Task <int> RetrieveTagRankAsync(Tag tag) { var tags = await RetrieveTagsAsync(tag.GuildId); return(tags.OrderByDescending(x => x.Uses).TakeWhile(x => x.Name != tag.Name).Count() + 1); }
public AttributeTag(Tag tag) : base("AT", tag) { }
public async Task AddTagAsync(Tag tag) { await _lexDbContext.Tags.AddAsync(tag); await _lexDbContext.SaveChangesAsync(); }
private void InitFields() { user1 = new User { Id = Guid.Parse("B71DBC28-6A02-47B1-8A2A-C6A5BFCD78AD"), Name = "TestUser1", Email = "*****@*****.**" }; fridge1 = new Fridge { Id = Guid.NewGuid(), UserId = Guid.Parse("B71DBC28-6A02-47B1-8A2A-C6A5BFCD78AD") }; user2 = new User { Id = Guid.Parse("B71DBC28-6A02-47B1-8A2A-C6A5BFCD78AD"), Name = "TestUser2", Email = "*****@*****.**" }; fridge2 = new Fridge { Id = Guid.NewGuid(), UserId = Guid.Parse("B71DBC28-AAAA-47B1-8A2A-C6A5BFCD78AD") }; productCategory1 = new ProductCategory { Id = Guid.Parse("A5ADA8E6-04E1-49CA-A701-1265E216D69A"), Name = "Product Category 1" }; productCategory2 = new ProductCategory { Id = Guid.Parse("94CAE204-3337-43FA-8C0E-24C927BACAC4"), Name = "Product Category 2" }; productCategory3 = new ProductCategory { Id = Guid.NewGuid(), Name = "Product Category 3" }; product1 = new BasicProduct { Id = Guid.Parse("9C750539-3CA6-4239-941F-805B81C38CD4"), Name = "Salmon", Description = "", ProductCategoryId = productCategory1.Id, UserId = Guid.Parse("B71DBC28-6A02-47B1-8A2A-C6A5BFCD78AD") }; product2 = new BasicProduct { Id = Guid.Parse("9D8FAC6F-C194-44E5-A6D5-B6F6DBDEBBD0"), Name = "Mustard", Description = "", ProductCategoryId = productCategory1.Id, UserId = Guid.Parse("B71DBC28-6A02-47B1-8A2A-C6A5BFCD78AD") }; product3 = new BasicProduct { Id = Guid.Parse("F1F5610D-F065-46D8-9208-D7D1A0CB8C27"), Name = "Brown Sugar", Description = "", ProductCategoryId = productCategory1.Id, UserId = Guid.Parse("B71DBC28-6A02-47B1-8A2A-C6A5BFCD78AD") }; product4 = new BasicProduct { Id = Guid.Parse("06BBED64-A505-492C-889B-472F7DAB0FAA"), Name = "Butter", Description = "", ProductCategoryId = productCategory2.Id, UserId = secondUserGuid }; product5 = new BasicProduct { Id = Guid.Parse("270B1180-45C6-4EE1-BC06-4819743859DC"), Name = "Cream", Description = "", ProductCategoryId = productCategory2.Id, UserId = secondUserGuid }; product6 = new BasicProduct { Id = Guid.Parse("002D754C-176B-4324-A42E-2DC32369074D"), Name = "Eggs", Description = "", ProductCategoryId = productCategory2.Id, UserId = secondUserGuid }; newProduct1 = new NewProduct { Id = Guid.NewGuid(), Name = "New product 1", Description = "", ProductCategoryId = productCategory1.Id, UserId = firstUserGuid }; newProduct2 = new NewProduct { Id = Guid.NewGuid(), Name = "New product 2", Description = "", ProductCategoryId = productCategory2.Id, UserId = secondUserGuid }; newProduct3 = new NewProduct { Id = Guid.NewGuid(), Name = "New product 3", Description = "", ProductCategoryId = productCategory2.Id, UserId = secondUserGuid }; recipe1 = new Recipe { Id = Guid.Parse("83BD2A25-83EA-47D0-9B7B-0E4D528CF8C2"), Description = "", Title = "Salmon recipe", UserId = Guid.Parse("B71DBC28-6A02-47B1-8A2A-C6A5BFCD78AD") }; recipe2 = new Recipe { Id = Guid.Parse("F795B317-DB3B-469F-9891-62C5CCC9DF5D"), Description = "", Title = "Scrambled eggs", UserId = Guid.Parse("B71DBC28-6A02-47B1-8A2A-C6A5BFCD78AD") }; recipe1Product1 = new RecipeProduct { Id = Guid.NewGuid(), RecipeId = recipe1.Id, ProductId = product1.Id }; recipe1Product2 = new RecipeProduct { Id = Guid.NewGuid(), RecipeId = recipe1.Id, ProductId = product2.Id }; recipe1Product3 = new RecipeProduct { Id = Guid.NewGuid(), RecipeId = recipe1.Id, ProductId = product3.Id }; recipe2Product4 = new RecipeProduct { Id = Guid.NewGuid(), RecipeId = recipe2.Id, ProductId = product4.Id }; recipe2Product5 = new RecipeProduct { Id = Guid.NewGuid(), RecipeId = recipe2.Id, ProductId = product5.Id }; recipe2Product6 = new RecipeProduct { Id = Guid.NewGuid(), RecipeId = recipe2.Id, ProductId = product6.Id }; fridge1Product1 = new FridgeProduct { Id = Guid.NewGuid(), FridgeId = fridge1.Id, ProductId = product1.Id }; fridge1Product2 = new FridgeProduct { Id = Guid.NewGuid(), FridgeId = fridge1.Id, ProductId = product2.Id }; fridge1Product3 = new FridgeProduct { Id = Guid.NewGuid(), FridgeId = fridge1.Id, ProductId = product3.Id }; fridge1Product4 = new FridgeProduct { Id = Guid.NewGuid(), FridgeId = fridge1.Id, ProductId = product4.Id }; fridge1Product5 = new FridgeProduct { Id = Guid.NewGuid(), FridgeId = fridge1.Id, ProductId = product5.Id }; fridge1Product6 = new FridgeProduct { Id = Guid.NewGuid(), FridgeId = fridge1.Id, ProductId = product6.Id }; tag1 = new Tag { Id = Guid.NewGuid(), Text = "tag1", RecipeTags = new List <RecipeTag>() }; tag2 = new Tag { Id = Guid.NewGuid(), Text = "tag2", RecipeTags = new List <RecipeTag>() }; tag3 = new Tag { Id = Guid.NewGuid(), Text = "tag3", RecipeTags = new List <RecipeTag>() }; recipe1tag1 = new RecipeTag { Id = Guid.NewGuid(), TagId = tag1.Id, RecipeId = recipe1.Id }; recipe1tag2 = new RecipeTag { Id = Guid.NewGuid(), TagId = tag1.Id, RecipeId = recipe1.Id }; recipe2tag3 = new RecipeTag { Id = Guid.NewGuid(), TagId = tag1.Id, RecipeId = recipe1.Id }; recipe1.RecipeProducts = new List <RecipeProduct> { recipe1Product1, recipe1Product2, recipe1Product3 }; recipe1.RecipeTags = new List <RecipeTag> { recipe1tag1, recipe1tag2 }; recipe2.RecipeProducts = new List <RecipeProduct>(); recipe2.RecipeTags = new List <RecipeTag> { recipe2tag3 }; tempUpdatingRecipe = new Recipe { RecipeProducts = new List <RecipeProduct>(), RecipeTags = new List <RecipeTag> { } }; recipesList = new List <Recipe> { recipe1, recipe2 }; productsList = new List <Product> { product1, product2, product3, product4, product5, product6 }; poorProductsRepositoryMock = new Mock <IProductsRepository>(); poorProductsRepositoryMock.Setup(pr => pr.GetProductById(It.IsAny <Guid>())) .Returns <Guid>(g => productsList.Where(p => p.Id == g).FirstOrDefault()); tagsList = new List <Tag> { tag1, tag2, tag3 }; poorTagsRepositoryMock = new Mock <ITagsRepository>(); poorTagsRepositoryMock.Setup(tr => tr.GetTagById(It.IsAny <Guid>())) .Returns <Guid>(g => tagsList.Where(t => t.Id == g).FirstOrDefault()); recipesRepositoryMock = new Mock <IRecipesRepository>(); recipesRepositoryMock.Setup(rr => rr.RemoveRecipeProduct(It.IsAny <RecipeProduct>())) .Callback <RecipeProduct>(rp => { tempUpdatingRecipe.RecipeProducts.Remove(rp); }); recipesRepositoryMock.Setup(rr => rr.AddProduct(It.IsAny <RecipeProduct>())) .Callback <RecipeProduct>(rp => { tempUpdatingRecipe.RecipeProducts.Add(rp); }); recipesRepositoryMock.Setup(rr => rr.RemoveProductById(It.IsAny <Guid>())) .Callback <Guid>(g => { tempUpdatingRecipe.RecipeProducts.Remove( tempUpdatingRecipe.RecipeProducts.Where(r => r.ProductId == g).FirstOrDefault()); }); recipesRepositoryMock.Setup(rr => rr.RemoveRecipeTag(It.IsAny <RecipeTag>())) .Callback <RecipeTag>(rt => { tempUpdatingRecipe.RecipeTags.Remove(rt); }); recipesRepositoryMock.Setup(rr => rr.RemoveTagById(It.IsAny <Guid>())) .Callback <Guid>(g => { tempUpdatingRecipe.RecipeTags.Remove( tempUpdatingRecipe.RecipeTags.Where(rt => rt.TagId == g).FirstOrDefault()); }); recipesRepositoryMock.Setup(rr => rr.AddTag(It.IsAny <RecipeTag>())) .Callback <RecipeTag>(rt => { tempUpdatingRecipe.RecipeTags.Add(rt); }); recipesRepositoryMock.Setup(rr => rr.GetRecipeById(It.IsAny <Guid>())) .Returns <Guid>(recipeId => { return(tempUpdatingRecipe); }); recipesRepositoryMock.Setup(rr => rr.ContainsProduct(It.IsAny <Guid>(), It.IsAny <Guid>())) .Returns <Guid, Guid>((recipeId, productId) => { return(tempUpdatingRecipe.RecipeProducts.Any(rp => rp.ProductId == productId)); }); recipesRepositoryMock.Setup(rr => rr.ContainsTag(It.IsAny <Guid>(), It.IsAny <Guid>())) .Returns <Guid, Guid>((recipeId, tagId) => { return(tempUpdatingRecipe.RecipeTags.Any(rt => rt.Id == tagId)); }); }
/// <summary> /// Process the next SASL step /// </summary> /// <param name="tag">Tag from the server</param> /// <returns>Tag to send the server</returns> public override Tag Step(Tag tag) { return(tag); }
public void EditTag(Tag tag) { _tagRepository.UpdateTag(tag); }
/** * Returns the css value of the style <b>font-size</b> in a pt-value. Possible font-size values: * <ul> * <li>a constant in px, in, cm, mm, pc, em or ex,</li> * <li>xx-small,</li> * <li>x-small,</li> * <li>small,</li> * <li>medium,</li> * <li>large,</li> * <li>x-large,</li> * <li>xx-large,</li> * <li>smaller (than tag's parent size),</li> * <li>larger (than tag's parent size),</li> * <li>a percentage (e.g font-size:250%) of tag's parent size,</li> * </ul> * @param tag to get the font size of. * @return float font size of the content of the tag in pt. */ virtual public float TranslateFontSize(Tag tag) { float size = Font.UNDEFINED; if (tag.CSS.ContainsKey(CSS.Property.FONT_SIZE)) { String value = tag.CSS[CSS.Property.FONT_SIZE]; if (Util.EqualsIgnoreCase(value, CSS.Value.XX_SMALL)) { size = 6.75f; } else if (Util.EqualsIgnoreCase(value, CSS.Value.X_SMALL)) { size = 7.5f; } else if (Util.EqualsIgnoreCase(value, CSS.Value.SMALL)) { size = 9.75f; } else if (Util.EqualsIgnoreCase(value, CSS.Value.MEDIUM)) { size = 12f; } else if (Util.EqualsIgnoreCase(value, CSS.Value.LARGE)) { size = 13.5f; } else if (Util.EqualsIgnoreCase(value, CSS.Value.X_LARGE)) { size = 18f; } else if (Util.EqualsIgnoreCase(value, CSS.Value.XX_LARGE)) { size = 24f; } else if (Util.EqualsIgnoreCase(value, CSS.Value.SMALLER)) { if (tag.Parent != null) { float parentSize = GetFontSize(tag.Parent); // if the font-size of the parent can be set in some memory the translation part is not needed anymore. if (parentSize == Font.UNDEFINED) { size = 9.75f; } else if (parentSize <= 6.75f) { size = parentSize - 1; } else if (parentSize == 7.5f) { size = 6.75f; } else if (parentSize == 9.75f) { size = 7.5f; } else if (parentSize == 12f) { size = 9.75f; } else if (parentSize == 13.5f) { size = 12f; } else if (parentSize == 18f) { size = 13.5f; } else if (parentSize == 24f) { size = 18f; } else if (parentSize < 24f) { size = parentSize * 0.85f; } else if (parentSize >= 24) { size = parentSize * 2 / 3; } } else { size = 9.75f; } } else if (Util.EqualsIgnoreCase(value, CSS.Value.LARGER)) { if (tag.Parent != null) { float parentSize = GetFontSize(tag.Parent); // if the font-size of the parent can be set in some memory the translation part is not needed anymore. if (parentSize == Font.UNDEFINED) { size = 13.5f; } else if (parentSize == 6.75f) { size = 7.5f; } else if (parentSize == 7.5f) { size = 9.75f; } else if (parentSize == 9.75f) { size = 12f; } else if (parentSize == 12f) { size = 13.5f; } else if (parentSize == 13.5f) { size = 18f; } else if (parentSize == 18f) { size = 24f; } else { size = parentSize * 1.5f; } } else { size = 13.5f; } } else if (utils.IsMetricValue(value) || utils.IsNumericValue(value)) { size = utils.ParsePxInCmMmPcToPt(value); } else if (utils.IsRelativeValue(value)) { float baseValue = Font.UNDEFINED; if (tag.Parent != null) { baseValue = GetFontSize(tag.Parent); } if (baseValue == Font.UNDEFINED) { baseValue = 12; } size = utils.ParseRelativeValue(value, baseValue); } } return(size); }
/// <summary> /// Сравнение деревьев /// </summary> /// <param name="other">Узел, с которым сравнивается текущий узел</param> /// <returns>-1 (меньше), 0 (равны), 1 (больше)</returns> public int CompareTo(TreeNode other) { return(Tag.CompareTo(other.Tag)); }
public void it_should_be_possible_to_construct_a_tag() { Tag tag = new Tag("This is a tag"); Assert.AreEqual("This is a tag", tag.Name); }
/// <summary> /// Serves as a hash of this type. /// </summary> /// <returns>A hash code for the current instance.</returns> public override int GetHashCode() { int hashCode = Tag.GetHashCode() ^ DataType.GetHashCode(); return(_Value != null ? hashCode ^ _Value.GetHashCode() : hashCode); }
public void AddTag(Tag tag) { _tagRepository.CreateTag(tag); }
public bool BeginWrite(Channel ch, Device dv, Tag item, string value) { IODriverDataTypes iODriverDataTypes = (IODriverDataTypes)Enum.Parse(typeof(IODriverDataTypes), item?.DataType); string address = item.Address; switch (iODriverDataTypes) { case IODriverDataTypes.BitOnByte: { string text3 = item.Address.Substring(1, 1); item.Address.Substring(2, 1); string text4 = item.Address.Remove(0, 3); int num3 = 0; int num4 = 0; switch (text3) { case "I": case "Q": case "U": { string[] array4 = text4.Split(new char[1] { '.' }, 4); address = "%" + text3 + "B" + array4[0] + "." + array4[1] + "."; num3 = int.Parse(array4[2]); num4 = int.Parse(array4[3]); break; } default: { string[] array3 = text4.Split(new char[1] { '.' }, 2); address = "%" + text3 + "B"; num3 = int.Parse(array3[0]); num4 = int.Parse(array3[1]); break; } } address = $"{address}{(num3 * 8 + num4) / 8}.{num4 % 8}"; break; } case IODriverDataTypes.BitOnWord: { string text = item.Address.Substring(1, 1); item.Address.Substring(2, 1); string text2 = item.Address.Remove(0, 3); int num = 0; int num2 = 0; switch (text) { case "I": case "Q": case "U": { string[] array2 = text2.Split(new char[1] { '.' }, 4); address = "%" + text + "B" + array2[0] + "." + array2[1] + "."; num = int.Parse(array2[2]); num2 = int.Parse(array2[3]); break; } default: { string[] array = text2.Split(new char[1] { '.' }, 2); address = "%" + text + "B"; num = int.Parse(array[0]); num2 = int.Parse(array[1]); break; } } address = $"{address}{(num * 16 + num2) / 8}.{num2 % 8}"; break; } } if (double.TryParse(value, out double result)) { _SendTo(new LSRequestMessage(LSNetBase.GetRequestType(iODriverDataTypes), (byte)dv.SlaveId, new _PieceData(address, iODriverDataTypes, result))); } return(false); }
public override void RunOnce() { //Создадим соединение if (!Connect()) { throw new Exception("Ошибка подключения! "); } //получить набор параметров и сохранить в параметрах for (int i = 0; i < _params.GetLength(0); i++) { if (_params[i, 4].StartsWith("in")) { if (_params[i, 2] == "tag") { Tag tag = _server.GetTag(_params[i, 3]); _cmd.Parameters[_params[i, 0]].Value = tag.Value; } else { _cmd.Parameters[_params[i, 0]].Value = _params[i, 3]; } } // if(_cmd.Parameters[_params[i, 0]].OracleType == OracleType.VarChar){ // _cmd.Parameters[_params[i, 0]].Size = ((string)(_cmd.Parameters[_params[i, 0]].Value)).Length; // } } if (_type == "update" || _type == "call") { _cmd.ExecuteNonQuery(); //Обработаем выходные параметры, если есть for (int i = 0; i < _params.GetLength(0); i++) { if (_params[i, 2] == "tag" && _params[i, 4].EndsWith("out")) { Tag tag = _server.GetTag(_params[i, 3]); tag.Value = _cmd.Parameters[_params[i, 0]].Value; _server.SetTag(tag); } } } else { OracleDataReader dr = _cmd.ExecuteReader(); try { if (_type == "scalar") { while (dr.Read()) { for (int i = 0; i < _maps.GetLength(0); i++) { Tag tag = _server.GetTag(_maps[i, 0]); if (dr[_maps[i, 1]] == DBNull.Value) { tag.Value = null; } else { tag.Value = dr[_maps[i, 1]]; } _server.SetTag(tag); } break;//только первую строку } } else { StringBuilder sb = new StringBuilder(); sb.AppendLine("<rows>"); while (dr.Read()) { sb.AppendLine("<row>"); for (int i = 0; i < dr.FieldCount; i++) { Type t = dr.GetFieldType(i); if (typeof(string) == t) { sb.AppendLine("<" + dr.GetName(i) + "><![CDATA[" + dr.GetValue(i) + "]]></" + dr.GetName(i) + ">"); } else if (typeof(DateTime) == t) { sb.AppendLine("<" + dr.GetName(i) + "><![CDATA[" + ((dr.GetValue(i) != null) ? ((DateTime)dr.GetValue(i)).ToString(DateTimeFormat.RUSSIANLONGFORMAT) : "") + "]]></" + dr.GetName(i) + ">"); } else { sb.AppendLine("<" + dr.GetName(i) + ">" + dr.GetValue(i) + "</" + dr.GetName(i) + ">"); } } sb.AppendLine("</row>"); LastRun = DateTime.Now; if (IsBreak) { break; } } if (!IsBreak) { sb.AppendLine("</rows>"); Tag tag = _server.GetTag(_maps[0, 0]); tag.Value = sb.ToString(); _server.SetTag(tag); } } } finally { dr.Close(); } } //Отключим соединение если не требуется хранить его if (!_keepalive) { Disconnect(); } }
public EntityAction Update(Tag entity) { EntityAction result = rep.Update(entity); return(result); }
/// <summary>Renders the item.</summary> /// <param name="output">The output.</param> /// <param name="item">The item to render.</param> /// <contract> /// <requires name="output" condition="not null" /> /// <requires name="item" condition="not null" /> /// </contract> protected override void RenderItem(HtmlTextWriter output, Item item) { Assert.ArgumentNotNull((object)output, "output"); Assert.ArgumentNotNull((object)item, "item"); string str1 = string.Empty; string str2 = string.Empty; string str3 = string.Empty; if (UploadedItems.Include(item)) { UploadedItems.RenewExpiration(); } string str4; int num1; if (item.TemplateID == TemplateIDs.MediaFolder || item.TemplateID == TemplateIDs.Folder || item.TemplateID == TemplateIDs.Node) { str4 = Themes.MapTheme("Applications/48x48/folder.png"); num1 = 48; int num2 = UserOptions.View.ShowHiddenItems ? item.Children.Count : this.GetVisibleChildCount(item); str1 = num2.ToString() + " " + Translate.Text(num2 == 1 ? "item" : "items"); } else { MediaItem mediaItem = (MediaItem)item; MediaUrlOptions thumbnailOptions = MediaUrlOptions.GetThumbnailOptions((MediaItem)item); num1 = MediaManager.HasMediaContent((Item)mediaItem) ? 72 : 48; thumbnailOptions.Width = num1; thumbnailOptions.Height = num1; thumbnailOptions.UseDefaultIcon = true; str4 = MediaManager.GetMediaUrl(mediaItem, thumbnailOptions); MediaMetaDataFormatter metaDataFormatter = MediaManager.Config.GetMetaDataFormatter(mediaItem.Extension); if (metaDataFormatter != null) { MediaMetaDataCollection metaData1 = mediaItem.GetMetaData(); MediaMetaDataCollection metaData2 = new MediaMetaDataCollection(); foreach (string key in metaData1.Keys) { metaData2[key] = HttpUtility.HtmlEncode(metaData1[key]); } if (str1 != null) { str1 = metaDataFormatter.Format(metaData2, MediaMetaDataFormatterOutput.HtmlNoKeys); } } str2 = new MediaValidatorFormatter().Format(mediaItem.ValidateMedia(), MediaValidatorFormatterOutput.HtmlPopup); ItemLink[] referrers = Globals.LinkDatabase.GetReferrers(item); if (referrers.Length > 0) { str3 = referrers.Length.ToString() + " " + Translate.Text(referrers.Length == 1 ? "usage" : "usages"); } } Tag tag = new Tag("a"); tag.Add("id", "I" + (object)item.ID.ToShortID()); tag.Add("href", "#"); tag.Add("onclick", "javascript:scForm.getParentForm().invoke('item:load(id=" + (object)item.ID + ")');return false"); if (UploadedItems.Include(item)) { tag.Add("class", "highlight"); } tag.Start(output); ImageBuilder imageBuilder1 = new ImageBuilder(); imageBuilder1.Src = str4; imageBuilder1.Class = "scMediaIcon"; imageBuilder1.Width = num1; imageBuilder1.Height = num1; ImageBuilder imageBuilder2 = imageBuilder1; string str5 = string.Empty; if (num1 < 72) { str5 = string.Format("padding:{0}px {0}px {0}px {0}px", (object)((72 - num1) / 2)); } if (!string.IsNullOrEmpty(str5)) { str5 = " style=\"" + str5 + "\""; } output.Write("<div class=\"scMediaBorder\"" + str5 + ">"); output.Write(imageBuilder2.ToString()); output.Write("</div>"); output.Write("<div class=\"scMediaTitle\">" + item.DisplayName + "</div>"); if (!string.IsNullOrEmpty(str1)) { output.Write("<div class=\"scMediaDetails\">" + str1 + "</div>"); } if (!string.IsNullOrEmpty(str2)) { output.Write("<div class=\"scMediaValidation\">" + str2 + "</div>"); } if (!string.IsNullOrEmpty(str3)) { output.Write("<div class=\"scMediaUsages\">" + str3 + "</div>"); } tag.End(output); }
public async Task <IActionResult> PostTask([FromForm] IList <IFormFile> inputs, [FromForm] IList <IFormFile> outputs, [FromForm] string taskDtoStr) { TaskDto taskDto = JsonConvert.DeserializeObject <TaskDto>(taskDtoStr); if (_context.Tasks.Any(t => t.Name.Equals(taskDto.Name))) { return(BadRequest(new { Message = "There is already a task called " + taskDto.Name })); } int currentUserId = int.Parse(User.FindFirst(JwtRegisteredClaimNames.Sub).Value); Entities.Task task = mapper.Map <Entities.Task>(taskDto); task.UserId = currentUserId; task.TimeSubmitted = DateTime.Now; task.IsPublic = false; // Add test cases to task object int n = inputs.Count; for (int i = 0; i < n; ++i) { StreamReader srin = new StreamReader(inputs[i].OpenReadStream()); Task <string> inputText = srin.ReadToEndAsync(); StreamReader srout = new StreamReader(outputs[i].OpenReadStream()); Task <string> outputText = srout.ReadToEndAsync(); string input = await inputText; string output = await outputText; srin.Close(); srout.Close(); task.TestCases.Add(new TestCase { Input = input, Output = output }); } _context.Tasks.Add(task); // Add tags whose names are not in DB foreach (TagDto tagDto in taskDto.Tags) { if (!await _context.Tags.AnyAsync(t => t.Name.Equals(tagDto.Name))) { _context.Tags.Add(new Tag { Name = tagDto.Name, Description = "", }); } } // Save task, test cases and new tags to DB (tasks and tags are not yet connected) await _context.SaveChangesAsync(); // Handle task TaskTag entities foreach (TagDto tagDto in taskDto.Tags) { Tag tag = await _context.Tags.FirstAsync(t => t.Name.Equals(tagDto.Name)); // Put tag ID along with newly added task ID into TaskTag entity _context.TaskTags.Add(new TaskTag { TaskId = task.Id, TagId = tag.Id, }); } // Save TaskTag entities await _context.SaveChangesAsync(); TaskDto responseDto = mapper.Map <TaskDto>(task); responseDto.TestCases = null; return(CreatedAtAction("GetTask", new { id = task.Id }, responseDto)); }
public TagOutput(Tag tag) { Id = tag.Id; Name = tag.Name; }
/** * Set the largest leading based on calculateLeading only. (Children not taken into account) * @param tag the tag */ public void SetLeading(Tag tag) { largestLeading = CalculateLeading(tag); }
public async Task <IActionResult> PutTask(int id, [FromForm] IList <IFormFile> inputs, [FromForm] IList <IFormFile> outputs, [FromForm] string taskDtoStr) { int currentUserId = int.Parse(User.FindFirst(JwtRegisteredClaimNames.Sub).Value); Entities.Task task = await _context.Tasks.SingleOrDefaultAsync(t => t.Id == id && (t.IsPublic || t.UserId == currentUserId)); if (task == null) { return(NotFound()); } if (task.UserId != currentUserId) { // Task doesn't belong to current user, edit not allowed return(Unauthorized()); } TaskDto taskDto = JsonConvert.DeserializeObject <TaskDto>(taskDtoStr); if (await _context.Tasks.AnyAsync(t => t.Id != id && t.Name.ToLower().Equals(taskDto.Name.ToLower()))) { return(BadRequest(new { Message = "There is already a task called " + taskDto.Name })); } // Load creator of task await _context.Entry(task).Reference(t => t.User).LoadAsync(); // Remove marked TCs foreach (TestCaseDto tcDto in taskDto.TestCases) { TestCase tc = new TestCase() { Id = tcDto.Id }; _context.TestCases.Attach(tc); _context.TestCases.Remove(tc); } // Add new TCs int n = inputs.Count; for (int i = 0; i < n; ++i) { StreamReader srin = new StreamReader(inputs[i].OpenReadStream()); Task <string> inputText = srin.ReadToEndAsync(); StreamReader srout = new StreamReader(outputs[i].OpenReadStream()); Task <string> outputText = srout.ReadToEndAsync(); string input = await inputText; string output = await outputText; srin.Close(); srout.Close(); task.TestCases.Add(new TestCase { Input = input, Output = output }); } // Load tasktags await _context.Entry(task).Collection(t => t.TaskTags).LoadAsync(); // Update fields according to DTO task.Name = taskDto.Name; task.Description = taskDto.Description; task.MemoryLimit = taskDto.MemoryLimit; task.TimeLimit = taskDto.TimeLimit; task.Origin = taskDto.Origin; // Handle tags // Add tags whose names are not in DB foreach (TagDto tagDto in taskDto.Tags) { if (!await _context.Tags.AnyAsync(t => t.Name.Equals(tagDto.Name))) { _context.Tags.Add(new Tag { Name = tagDto.Name, Description = "", }); } } // Get old tag ids from TaskTags var oldTagIds = new List <int>(); foreach (TaskTag tt in task.TaskTags) { oldTagIds.Add(tt.TagId); } // Remove TaskTags _context.TaskTags.RemoveRange(task.TaskTags); // Save changes so that new Tags get ids and TaskTags get really removed await _context.SaveChangesAsync(); // Add new TaskTags to task foreach (TagDto tagDto in taskDto.Tags) { Tag tag = await _context.Tags.FirstAsync(t => t.Name.Equals(tagDto.Name)); _context.TaskTags.Add(new TaskTag { TaskId = task.Id, TagId = tag.Id, }); } // Save changes so that TaskTags are really added await _context.SaveChangesAsync(); // Remove unused Tags, check only old ones foreach (int tId in oldTagIds) { if (!await _context.TaskTags.AnyAsync(tt => tt.TagId == tId)) { _context.Tags.Remove(await _context.Tags.FindAsync(tId)); } } // Save changes try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TaskExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public override int SaveChanges() { /* http://stackoverflow.com/a/6157071 */ ChangeTracker.DetectChanges(); // Important! ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext; List <ObjectStateEntry> objectStateEntryList = ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted) .ToList(); foreach (ObjectStateEntry entry in objectStateEntryList) { var props = entry.GetModifiedProperties(); string modifiedProperty = props.FirstOrDefault(); bool isUserViewAction = props.Count() == 1 && modifiedProperty == "Views"; bool isProfileUpdateAction = (entry.Entity is Entities.KbUser); // if only if (!entry.IsRelationship && !isUserViewAction && !isProfileUpdateAction) { string operationDescription = ""; var act = new Activities(); act.ActivityDate = DateTime.Now; switch (entry.State) { case EntityState.Added: operationDescription = "Added "; break; case EntityState.Deleted: operationDescription = "Deleted "; break; case EntityState.Modified: operationDescription = "Modified "; break; default: break; } if (entry.Entity is Article) { Article a = ((Article)entry.Entity); operationDescription += " Article "; act.Information = "Title: " + a.Title + " Id:" + a.Id.ToString(); act.UserId = a.Author; } else if (entry.Entity is Category) { Category c = ((Category)entry.Entity); operationDescription += " Category "; act.Information = "Name: " + c.Name + " Id:" + c.Id.ToString(); act.UserId = c.Author; } else if (entry.Entity is Tag) { Tag t = ((Tag)entry.Entity); operationDescription += " Tag "; act.Information = "Name: " + t.Name + " Id:" + t.Id.ToString(); act.UserId = t.Author; } else if (entry.Entity is ArticleTag) { ArticleTag at = ((ArticleTag)entry.Entity); operationDescription += " ArticleTag "; act.Information = "ArticleId: " + at.ArticleId + " TagId:" + at.TagId.ToString(); act.UserId = at.Author; } else if (entry.Entity is Attachment) { Attachment a = ((Attachment)entry.Entity); operationDescription += " Attachment "; act.Information = "ArticleId: " + a.ArticleId + " Id:" + a.Id.ToString(); act.UserId = a.Author; } else if (entry.Entity is Settings) { var s = ((Settings)entry.Entity); operationDescription += " Settings "; act.Information = "Settings updated"; act.UserId = s.Author; } act.Operation = operationDescription; List <SqlParameter> procParams = new List <SqlParameter>(); procParams.Add(new SqlParameter("1", act.UserId)); procParams.Add(new SqlParameter("2", act.ActivityDate)); procParams.Add(new SqlParameter("3", act.Operation)); procParams.Add(new SqlParameter("4", act.Information)); this.Database.ExecuteSqlCommand( "Insert Into Activities(UserId,ActivityDate,Operation,Information) " + "Values(@1,@2,@3,@4 )", procParams.ToArray()); /* * switch (entry.State) * { * case EntityState.Added: * // write log... * break; * case EntityState.Deleted: * // write log... * break; * case EntityState.Modified: * { * foreach (string propertyName in * entry.GetModifiedProperties()) * { * DbDataRecord original = entry.OriginalValues; * string oldValue = original.GetValue( * original.GetOrdinal(propertyName)) * .ToString(); * * CurrentValueRecord current = entry.CurrentValues; * string newValue = current.GetValue( * current.GetOrdinal(propertyName)) * .ToString(); * * if (oldValue != newValue) // probably not necessary * { * Log.WriteAudit( * "Entry: {0} Original :{1} New: {2}", * entry.Entity.GetType().Name, * oldValue, newValue); * } * } * break; * } * }*/ } } return(base.SaveChanges()); }
public static GameObject SetupDiet(GameObject prefab, HashSet <Tag> consumed_tags, Tag producedTag, float caloriesPerKg) { Diet.Info[] infos = new Diet.Info[1] { new Diet.Info(consumed_tags, producedTag, caloriesPerKg, 1f, null, 0f, false, false) }; Diet diet = new Diet(infos); CreatureCalorieMonitor.Def def = prefab.AddOrGetDef <CreatureCalorieMonitor.Def>(); def.diet = diet; SolidConsumerMonitor.Def def2 = prefab.AddOrGetDef <SolidConsumerMonitor.Def>(); def2.diet = diet; return(prefab); }
private void OnShowAllClicked(object sender, Windows.UI.Xaml.RoutedEventArgs e) { NavigationService.Instance.Frame.Navigate(typeof(ShowAllView), (CurrentQuery, (sender as Button).Tag.ToString())); }
public LongString(Tag tag) : base("LO", tag) { }