public Unit CreateUnit(IUnitSystem system, double factor, Dimension dimension) { Check.SystemKnowsDimension(system, dimension); var unit = new DerivedUnit(system, factor, dimension); return unit; }
public static TileMap LoadMap(int xLocation, int yLocation, Dimension dimension) { TileMap t = new TileMap(); t.xLoc = xLocation; t.yLoc = yLocation; t.data = new byte[MapWidth][][]; for (int x = 0; x < MapWidth; x++) { t.data[x] = new byte[MapHeight][]; for (int y = 0; y < MapHeight; y++) { t.data[x][y] = new byte[MapDepth]; } } FileStream fStream = new FileStream("Maps\\ovr" + ((yLocation * 16) + xLocation) + ".map", FileMode.Open); for (int y = 0; y < MapHeight; y++) { for (int x = 0; x < MapWidth; x++) { for (int z = 0; z < MapDepth; z++) { t.data[x][y][z] = (byte)fStream.ReadByte(); } } } fStream.Close(); return t; }
public static DimensionInfo CreateDimensionInfo(Dimension dim) { if (dim == null) return null; DimensionInfo info = new DimensionInfo(); info.Caption = dim.Caption; info.Description = dim.Description; info.DimensionType = (DimensionInfoTypeEnum)(dim.DimensionType); info.Name = dim.Name; info.WriteEnabled = dim.WriteEnabled; info.UniqueName = dim.UniqueName; // Информация о предках if (dim.ParentCube != null) { info.ParentCubeId = dim.ParentCube.Name; info.CustomProperties.Add(new PropertyInfo(InfoBase.CUBE_CAPTION, dim.ParentCube.Caption)); } // Свойства foreach (Property prop in dim.Properties) { // PropertyInfo pi = new PropertyInfo(prop.Name, prop.Type, prop.Value); PropertyInfo pi = new PropertyInfo(prop.Name, prop.Value); info.Properties.Add(pi); } return info; }
protected override Point MatchCoordinate(Dimension dimension) { Match match = MatchRegex(@"^(-?\d+\.?\d*)\s+(-?\d+\.?\d*)\s+(-?\d+\.?\d*)\s+(-?\d+\.?\d*)"); if (match.Success) { geometryDimension = Dimension.Xyzm; return new Point(double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture), double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), double.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture), double.Parse(match.Groups[4].Value, CultureInfo.InvariantCulture)); } match = MatchRegex(@"^(-?\d+\.?\d*)\s+(-?\d+\.?\d*)\s+(-?\d+\.?\d*)"); if (match.Success) { if (dimension == Dimension.Xym) { geometryDimension = Dimension.Xym; return new Point(double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture), double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), null, double.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture)); } else { geometryDimension = Dimension.Xyz; return new Point(double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture), double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), double.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture)); } } geometryDimension = Dimension.Xy; match = MatchRegex(@"^(-?\d+\.?\d*)\s+(-?\d+\.?\d*)"); return new Point(double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture), double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture)); }
public void ReadPacket(IMinecraftStream stream) { EntityID = stream.ReadInt32(); stream.ReadString(); // Unused Seed = stream.ReadInt64(); Dimension = (Dimension)stream.ReadInt8(); }
public LifeBoard(Dimension dim) { width = dim.Width; height = dim.Height; size = dim.Size; array = new bool[width, height]; }
public LightSequenceBar(LightSequence sequence, Point pivot, Dimension tileSize, int indent) : base(Geometry.ConstructRectangle(pivot, tileSize)) { this.sequence = sequence; this.tileSize = tileSize; this.indent = indent; }
private static void ImportD5() { Dictionary<string,string> dict = new Dictionary<string,string>(11); //dict.Add("Peroid","期"); //dict.Add("DaXiao","大小"); //dict.Add("DanShuang","单双"); //dict.Add("ZiHe","质合"); //dict.Add("Lu012","012路"); //dict.Add("He","和"); //dict.Add("HeWei","和尾"); //dict.Add("Ji","积"); //dict.Add("JiWei","积尾"); //dict.Add("KuaDu","跨度"); //dict.Add("AC","AC"); //dict.Add("DaXiaoBi", "大小比"); //dict.Add("ZiHeBi", "质合比"); //dict.Add("DanShuangBi", "单双比"); //dict.Add("Lu012Bi", "012路比"); foreach (var kp in dict) { Dimension dim = new Dimension(); dim.Name = kp.Value; dim.Code = kp.Key; dim.Seq = 100; DimensionBiz.Instance.Add(dim); } }
public String GetRegionDirectory(Dimension dim) { String path; switch (dim) { case Dimension.Overworld: path = String.Format("{0}{1}region", WorldDir, Path.DirectorySeparatorChar); break; case Dimension.Nether: path = String.Format("{0}{1}DIM-1{1}region", WorldDir, Path.DirectorySeparatorChar); break; case Dimension.End: path = String.Format("{0}{1}DIM1{1}region", WorldDir, Path.DirectorySeparatorChar); break; default: throw new Exception("Unrecognized dimension."); } if (Directory.Exists(path)) return path; else { switch (dim) { case Dimension.Overworld: return String.Format("{0}{1}worlds{1}overworld{1}regions", WorldDir, Path.DirectorySeparatorChar); case Dimension.Nether: return String.Format("{0}{1}worlds{1}nether{1}regions", WorldDir, Path.DirectorySeparatorChar); case Dimension.End: return String.Format("{0}{1}worlds{1}the_end{1}regions", WorldDir, Path.DirectorySeparatorChar); default: throw new Exception("Unrecognized dimension."); } } }
public static Bitmap Render(Dimension d, LatticeLayoutMethod method, bool ShowOnlyMultilevelRelationships) { if (ShowOnlyMultilevelRelationships) { if (d.Attributes.Count == 1) { //avoid an error ShowOnlyMultilevelRelationships = false; } } LatticeDrawing ld = new LatticeDrawing(d.Name); ld.LayoutMethod = method; foreach (DimensionAttribute a in d.Attributes) { ld.Nodes.Add(a.ID, new LatticeNode(a.Name)); if (d.KeyAttribute == a) { ld.Nodes[a.ID].IsKey = true; } ld.Nodes[a.ID].Visible = a.AttributeHierarchyVisible; ld.Nodes[a.ID].Enabled = a.AttributeHierarchyEnabled; } foreach (DimensionAttribute a in d.Attributes) { foreach (AttributeRelationship r in a.AttributeRelationships) { ld.Nodes[a.ID].Relationships.Add(new LatticeRelationship(ld.Nodes[r.AttributeID], r.RelationshipType, r.Visible)); if (d.KeyAttribute != a) { ld.Nodes[r.AttributeID].NonKeyReferenceCount++; } } } if (ShowOnlyMultilevelRelationships) { foreach (DimensionAttribute a in d.Attributes) { if (a.AttributeRelationships.Count == 0 && ld.Nodes[a.ID].NonKeyReferenceCount == 0) { ld.Nodes.Remove(a.ID); } } foreach (LatticeNode ln in ld.Nodes.Values) { for (int i = 0; i < ln.Relationships.Count; i++) { LatticeRelationship lr = ln.Relationships[i]; if (!ld.Nodes.ContainsValue(lr.node)) { ln.Relationships.Remove(lr); i--; } } } } ld.LayoutMethod = method; return ld.Render(); }
public CubicGrid(int3 dimensions, float valueMin, float valueMax, Dimension gradientDirection) { Dimensions = dimensions; Values = new float[dimensions.Z, dimensions.Y, dimensions.X]; float Step = valueMax - valueMin; if (gradientDirection == Dimension.X) Step /= Math.Max(1, dimensions.X - 1); else if (gradientDirection == Dimension.Y) Step /= Math.Max(1, dimensions.Y - 1); else if (gradientDirection == Dimension.Z) Step /= Math.Max(1, dimensions.Z - 1); for (int z = 0; z < dimensions.Z; z++) for (int y = 0; y < dimensions.Y; y++) for (int x = 0; x < dimensions.X; x++) { float Value = valueMin; if (gradientDirection == Dimension.X) Value += x * Step; if (gradientDirection == Dimension.Y) Value += y * Step; if (gradientDirection == Dimension.Z) Value += z * Step; Values[z, y, x] = Value; } Spacing = new float3(1f / Math.Max(1, dimensions.X - 1), 1f / Math.Max(1, dimensions.Y - 1), 1f / Math.Max(1, dimensions.Z - 1)); }
void HandleTouchUpInside (object sender, EventArgs e) { const string ACCESS_KEY = ""; const string SECRET_KEY = ""; IAmazonCloudWatch cw = Amazon.AWSClientFactory.CreateAmazonCloudWatchClient (ACCESS_KEY, SECRET_KEY, Amazon.RegionEndpoint.USWest1); string measureName = "CPUUtilization"; GetMetricStatisticsRequest request = new GetMetricStatisticsRequest (); request.StartTime = DateTime.Now.AddDays (-1); request.Namespace = "AWS/EC2"; request.Period = 5 * 60; var dimensions = new Dimension (); dimensions.Name = "InstanceType"; dimensions.Value = "t1.micro"; request.Dimensions = new List<Dimension>{ dimensions }; request.MetricName = measureName; request.Statistics = new List<string>{"Average", "Maximum", "Minimum"}; request.EndTime = DateTime.Now; List<Datapoint> datapoints = cw.GetMetricStatistics(request).Datapoints; datapoints.ForEach(d => this.View.Add(new UILabel(){ Text = String.Format("Min: {0} Max: {1} Average: {3} Unit: {4}\n", d.Minimum, d.Maximum, d.Average, d.Unit), Frame = (new RectangleF(20, 40*datapoints.FindIndex(dp => dp==d), 280, 21)) })); }
public void ThenExponentsDetermineEquality() { var dim1 = new Dimension(1, 2, 3); var dim2 = new Dimension(1, 2, 3); var dim3 = new Dimension(3, 2, 1); Assert.AreEqual(dim1, dim2); Assert.AreEqual(dim1.GetHashCode(), dim1.GetHashCode()); Assert.AreNotEqual(dim1, dim3); Assert.AreNotEqual(dim1.GetHashCode(), dim3.GetHashCode()); Assert.AreNotEqual(dim2, dim3); Assert.AreNotEqual(dim2.GetHashCode(), dim3.GetHashCode()); var dim4 = new Dimension(1); var dim5 = new Dimension(1); Assert.AreEqual(dim4, dim5); Assert.AreEqual(dim4.GetHashCode(), dim5.GetHashCode()); var dim6 = new Dimension(); var dim7 = new Dimension(); Assert.AreEqual(dim6, dim7); Assert.AreEqual(dim6.GetHashCode(), dim7.GetHashCode()); }
public static Dimension Discharge() { Dimension d = new Dimension(); d.SetPower(DimensionBase.Length, 3.0); d.SetPower(DimensionBase.Time, -1.0); return d; }
public void testBlockDimensions() { Dimension frame = new Dimension(320,240); for(int numY = 1; numY < 10; numY ++) { for(int numX = 1; numX < 10; numX++) { Console.WriteLine("numX: %d\tnumY: %d\n", numX, numY); Dimension block = new Dimension(frame.Width / numX, frame.Height / numY); for(int i = 0; i < numY; i++) for(int j = 0; j < numX; j++) { int testStart = (block.Width*j) + (frame.Width*block.Height*i); int testEnd = testStart + block.Width + (frame.Width*(block.Height-1)); int specX = (frame.Width * j)/numX; int specY = (frame.Height *i)/numY; int specStart = (frame.Width*specY) + specX; int specEndX = (frame.Width * (j+1))/numX; int specEndY = (frame.Height *(i+1))/numY; int specEnd = (frame.Width*(specEndY - 1)) + specEndX; if(specEnd != testEnd || specStart != testStart) { Console.WriteLine("Spec:\t\tTest\n%d\t\t%d\n", specEnd, testEnd); Console.WriteLine("%d\t\t%d\n", specStart, testStart); } } } } }
public static Image Clip(this Image imgPhoto, int width, int height, bool stretch) { if (!stretch && (imgPhoto.Width <= width && imgPhoto.Height <= height)) return imgPhoto; // detect if portrait if (imgPhoto.Height > imgPhoto.Width) { // swap int a = width; width = height; height = a; } var d = new Dimension(imgPhoto.Width, imgPhoto.Height); double scale = d.NewSizeScaleFactor(new Dimension(width, height), stretch); var newD = scale * d; if (stretch) { if (!(newD.Width == width || newD.Height == height)) throw new Exception("Stretching algo has some error"); } var bmPhoto = new Bitmap(imgPhoto, new Size(newD.Width, newD.Height)); return bmPhoto; }
/** * Private constructor. */ private Unit(List ids, Dimension dim, double scale, double offset) { this.m_ids = checkIds(ids); this.m_dim = dim; this.m_scale = scale; this.m_offset = offset; }
public void ThenStartingZerosAreNotIgnored() { var dim1 = new Dimension(0, 0, 1); var dim2 = new Dimension(1); Assert.AreNotEqual(dim1, dim2); }
public Renderable(String texturePath) { Texture = new Bitmap(texturePath); Position = new Coordinate(); Dimension = new Dimension(); PinPositions = new List<Coordinate>(); }
public KnownUnit CreateUnit(IUnitSystem system, double factor, Dimension dimension, string symbol, string name, bool inherentPrefix) { var unit = new KnownUnit(system, factor, dimension, symbol, name, inherentPrefix); return unit; }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button> (Resource.Id.getcloudwatchdata); EditText cloudwatchdata = FindViewById<EditText> (Resource.Id.cloudwatchdata); button.Click += delegate { const string ACCESS_KEY = ""; const string SECRET_KEY = ""; IAmazonCloudWatch cw = Amazon.AWSClientFactory.CreateAmazonCloudWatchClient (ACCESS_KEY, SECRET_KEY, Amazon.RegionEndpoint.USWest1); string measureName = "CPUUtilization"; GetMetricStatisticsRequest request = new GetMetricStatisticsRequest (); request.StartTime = DateTime.Now.AddDays (-1); request.Namespace = "AWS/EC2"; request.Period = 5 * 60; var dimensions = new Dimension (); dimensions.Name = "InstanceType"; dimensions.Value = "t1.micro"; request.Dimensions = new List<Dimension>{ dimensions }; request.MetricName = measureName; request.Statistics = new List<string>{"Average", "Maximum", "Minimum"}; request.EndTime = DateTime.Now; List<Datapoint> datapoints = cw.GetMetricStatistics(request).Datapoints; datapoints.ForEach(d => cloudwatchdata.Text = String.Format("Min: {0} Max: {1} Average: {3} Unit: {4}\n", d.Minimum, d.Maximum, d.Average, d.Unit)); }; }
public static Dimension Velocity() { Dimension d = new Dimension(); d.SetPower(DimensionBase.Length, 1.0); d.SetPower(DimensionBase.Time, -1.0); return d; }
public void ThenTrailingZerosAreIgnored() { var dim1 = new Dimension(1, 2, 3, 0, 0); var dim2 = new Dimension(1, 2, 3); Assert.AreEqual(dim1, dim2); Assert.AreEqual(dim1.GetHashCode(), dim2.GetHashCode()); }
public static Dimension Pressure() { Dimension d = new Dimension(); d.SetPower(DimensionBase.Mass, 1.0); d.SetPower(DimensionBase.Length, -1.0); d.SetPower(DimensionBase.Time, -2.0); return d; }
private void Test1() { string s = Dimension.getDataTypeName(Dimension.DataType.Double); Debug.Assert(s == "Double"); Dimension d = new Dimension(DimensionId.Id.Blue_u16); return; }
internal void FromDimension(Dimension d) { this.SetAllNull(); if (d.Measure != null) this.Measure = d.Measure.Value; if (d.Name != null) this.Name = d.Name.Value; if (d.UniqueName != null) this.UniqueName = d.UniqueName.Value; if (d.Caption != null) this.Caption = d.Caption.Value; }
public void initializeLevel(Dimension dim) { /*take the width and height of the level, and the fact that we are going to allow 3 tiles to sit in the same location, hense the 3D space. we may even use this depth as our means of layering elements such as items over top of other tiles. each tile would have a desired depth, 0, 1, or 2. We would render them as best we could. */ grid = new TiledObj[dim.width, dim.height, depth]; objList = new List<TiledObj> (); resolveTileList = new List<TiledObj> (); }
private void Test1() { string s = Dimension.getDataTypeName(Dimension.DataType.Double); Assert(s == "Double"); Dimension d = new Dimension(Dimension.Field.Field_Blue, Dimension.DataType.Float); return; }
public IPacket ReadPacket(IMinecraftDataReader reader) { Dimension = (Dimension) reader.ReadInt(); Difficulty = (Difficulty) reader.ReadByte(); GameMode = (GameMode) reader.ReadByte(); LevelType = reader.ReadString(); return this; }
public RespawnPacket(Dimension dimension, Difficulty difficulty, GameMode gameMode, string levelType) { Dimension = dimension; Difficulty = difficulty; GameMode = gameMode; WorldHeight = 256; LevelType = levelType; }
private void CreateDimension(short AxisOrdinal, HtmlTable hostTable, Dimension dim) { HtmlTableRow tr = new HtmlTableRow(); HtmlTableCell td; System.Web.UI.WebControls.Button btn; // --- node contr col-- tr = new HtmlTableRow(); td = new HtmlTableCell(); td.Attributes.Add("class", "sel_C1"); td.NoWrap = true; tr.Cells.Add(td); // --- node name col-- td = new HtmlTableCell(); btn = new System.Web.UI.WebControls.Button(); if (dim.IsOpen) { btn.ToolTip = "Close"; btn.ID = "sel_dclose:" + dim.UniqueName; btn.CssClass = "sel_close"; } else { btn.ToolTip = "Open"; btn.ID = "sel_dopen:" + dim.UniqueName; btn.CssClass = "sel_open"; } td.Controls.Add(btn); Literal lit = new Literal(); lit.Text = dim.Name; td.Controls.Add(lit); td.Attributes.Add("class", "sel_C"); td.NoWrap = true; tr.Cells.Add(td); // --- node select col-- td = new HtmlTableCell(); td.Attributes.Add("class", "sel_C"); td.NoWrap = true; tr.Cells.Add(td); hostTable.Rows.Add(tr); if (dim.IsOpen == false) { return; } // members level depth=0 for (int j = 0; j < dim.Hierarchies.Count; j++) { if (dim.Hierarchies[j].Axis.Ordinal == AxisOrdinal) // only if axis matches { CreateHierarchy(AxisOrdinal, hostTable, dim.Hierarchies[j], 1); //treedepth is 1 because 0 is dim } } }
private void LoadSelectTable(HtmlTable hostTable, string Header, short AxisOrdinal) { HtmlTableRow tr; HtmlTableCell td; //header tr = new HtmlTableRow(); td = new HtmlTableCell(); td.InnerText = Header; td.ColSpan = 3; td.Attributes.Add("class", "sel_H"); td.NoWrap = true; tr.Cells.Add(td); td = new HtmlTableCell(); td.NoWrap = true; tr.Cells.Add(td); td = new HtmlTableCell(); td.NoWrap = true; tr.Cells.Add(td); hostTable.Rows.Add(tr); if (AxisOrdinal == 2) { Dimension[] dims = _report.Schema.Dimensions.ToSortedByNameArray(); for (int i = 0; i < dims.Length; i++) { Dimension dim = dims[i]; if (dim.Hierarchies.Count == 1) { if (dim.Hierarchies[0].Axis.Ordinal == AxisOrdinal) //only if axis is 2 { CreateHierarchy(AxisOrdinal, hostTable, dim.Hierarchies[0], 0); } } else { Hierarchy[] hiers = dim.Hierarchies.ToSortedByNameArray(); for (int j = 0; j < hiers.Length; j++) { Hierarchy hier = hiers[j]; if (hier.Axis.Ordinal == 2) { this.CreateDimension(AxisOrdinal, hostTable, dim); break; //go to next dim, dim will create hiers itself } } } } } else { for (int i = 0; i < _report.Axes[AxisOrdinal].Hierarchies.Count; i++) { Hierarchy hier = _report.Axes[AxisOrdinal].Hierarchies[i]; //not alph order //hier header CreateHierarchy(AxisOrdinal, hostTable, hier, 0); } } }
public static void SetValue(this StyleSheet styleSheet, StyleValueHandle valueHandle, Dimension value) { // Undo/Redo Undo.RegisterCompleteObjectUndo(styleSheet, BuilderConstants.ChangeUIStyleValueUndoMessage); styleSheet.dimensions[valueHandle.valueIndex] = value; }
/// <summary> /// Performs message encoding of a DataMatrix message using the algorithm described in annex P /// of ISO/IEC 16022:2000(E). /// </summary> /// <param name="msg">the message</param> /// <param name="shape">requested shape. May be {@code SymbolShapeHint.FORCE_NONE},{@code SymbolShapeHint.FORCE_SQUARE} or {@code SymbolShapeHint.FORCE_RECTANGLE}.</param> /// <param name="minSize">the minimum symbol size constraint or null for no constraint</param> /// <param name="maxSize">the maximum symbol size constraint or null for no constraint</param> /// <param name="defaultEncodation">encoding mode to start with</param> /// <returns>the encoded message (the char values range from 0 to 255)</returns> public static String encodeHighLevel(String msg, SymbolShapeHint shape, Dimension minSize, Dimension maxSize, int defaultEncodation) { //the codewords 0..255 are encoded as Unicode characters Encoder[] encoders = { new ASCIIEncoder(), new C40Encoder(), new TextEncoder(), new X12Encoder(), new EdifactEncoder(), new Base256Encoder() }; var context = new EncoderContext(msg); context.setSymbolShape(shape); context.setSizeConstraints(minSize, maxSize); if (msg.StartsWith(MACRO_05_HEADER) && msg.EndsWith(MACRO_TRAILER)) { context.writeCodeword(MACRO_05); context.setSkipAtEnd(2); context.Pos += MACRO_05_HEADER.Length; } else if (msg.StartsWith(MACRO_06_HEADER) && msg.EndsWith(MACRO_TRAILER)) { context.writeCodeword(MACRO_06); context.setSkipAtEnd(2); context.Pos += MACRO_06_HEADER.Length; } int encodingMode = defaultEncodation; //Default mode switch (encodingMode) { case Encodation.BASE256: context.writeCodeword(HighLevelEncoder.LATCH_TO_BASE256); break; case Encodation.C40: context.writeCodeword(HighLevelEncoder.LATCH_TO_C40); break; case Encodation.X12: context.writeCodeword(HighLevelEncoder.LATCH_TO_ANSIX12); break; case Encodation.TEXT: context.writeCodeword(HighLevelEncoder.LATCH_TO_TEXT); break; case Encodation.EDIFACT: context.writeCodeword(HighLevelEncoder.LATCH_TO_EDIFACT); break; case Encodation.ASCII: break; default: throw new InvalidOperationException("Illegal mode: " + encodingMode); } while (context.HasMoreCharacters) { encoders[encodingMode].encode(context); if (context.NewEncoding >= 0) { encodingMode = context.NewEncoding; context.resetEncoderSignal(); } } int len = context.Codewords.Length; context.updateSymbolInfo(); int capacity = context.SymbolInfo.dataCapacity; if (len < capacity && encodingMode != Encodation.ASCII && encodingMode != Encodation.BASE256 && encodingMode != Encodation.EDIFACT) { context.writeCodeword('\u00fe'); //Unlatch (254) } //Padding StringBuilder codewords = context.Codewords; if (codewords.Length < capacity) { codewords.Append(PAD); } while (codewords.Length < capacity) { codewords.Append(randomize253State(codewords.Length + 1)); } return(context.Codewords.ToString()); }
public int UpdateVideo(int VideoId, string Title, VideoStatus Status, string Object, string Description, int?CategoryId, int ModifierId, HttpPostedFile Image, bool?AutoResize, bool DeleteOldImage, Languages?lan, HttpPostedFile VideoFile) { if (lan == null) { lan = Languages.Default; } var video = GetVideo(VideoId); video.Title = Title; video.Status = (byte)Status; video.Object = Object; video.Description = Description; video.CategoryId = CategoryId; video.DateModified = DateTime.Now; video.UniqueName = StringUtils.ToURL(Title); video.ModifierId = ModifierId; video.Language = (short)lan; MediaData.SubmitChanges(); string path = WebContext.Server.MapPath(Path.Combine(WebContext.StartDir, Folders.VideosFolder)); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var oldImage = video.ThumbImage; bool generateThumb = Image != null && Image.ContentLength > 0; if (VideoFile != null && VideoFile.ContentLength > 0) { string videoName = Path.GetFileNameWithoutExtension(VideoFile.FileName); videoName = string.Format("{0}_{1}{2}", videoName, video.VideoId, Path.GetExtension(VideoFile.FileName)); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = Path.Combine(path, videoName); VideoFile.SaveAs(path); //ShellFile so = ShellFile.FromFilePath(path); //decimal nanoseconds; //decimal.TryParse(so.Properties.System.Media.Duration.Value.ToString(), out nanoseconds); //decimal seconds = nanoseconds * (decimal)0.0000001; //video.VideoLength = seconds; if (!generateThumb) { string imageName = Path.GetFileNameWithoutExtension(videoName) + ".Jpg"; string imagePath = Path.Combine(WebContext.Server.MapPath("~/" + Folders.VideoThumbsFolder), imageName); //so.Thumbnail.Bitmap.Save(imagePath); VideoCategory cat = GetVideoCategory(CategoryId.Value); if (cat.ThumbWidth > 0 && cat.ThumbHeight > 0) { ImageUtils.CropImage(imagePath, imagePath, (int)cat.ThumbWidth, (int)cat.ThumbHeight, ImageUtils.AnchorPosition.Default); } else { Config cfg = new Config(); Dimension dim = new Dimension(cfg.GetKey(lw.CTE.parameters.VideoThumbSize)); if (dim.Width > 0 && dim.Height > 0) { ImageUtils.CropImage(imagePath, imagePath, (int)dim.Width, (int)dim.Height, ImageUtils.AnchorPosition.Default); } } video.ThumbImage = imageName; } video.VideoFile = videoName; MediaData.SubmitChanges(); } DeleteOldImage = DeleteOldImage || (Image != null && Image.ContentLength > 0); if (DeleteOldImage && !StringUtils.IsNullOrWhiteSpace(video.ThumbImage)) { if (File.Exists(Path.Combine(path, oldImage))) { File.Delete(Path.Combine(path, oldImage)); } video.ThumbImage = ""; } if (AutoResize != null && AutoResize.Value == true) { VideoCategory cat = GetVideoCategory(CategoryId.Value); if (cat.ThumbWidth > 0 && cat.ThumbHeight > 0) { //ImageUtils.Resize(path, path, (int)cat.ThumbWidth, (int)cat.ThumbHeight); ImageUtils.CropImage(path, path, (int)cat.ThumbWidth, (int)cat.ThumbHeight, ImageUtils.AnchorPosition.Default); } else { Config cfg = new Config(); Dimension dim = new Dimension(cfg.GetKey(lw.CTE.parameters.VideoThumbSize)); if (dim.Width > 0 && dim.Height > 0) { ImageUtils.CropImage(path, path, (int)dim.Width, (int)dim.Height, ImageUtils.AnchorPosition.Default); } } } MediaData.SubmitChanges(); return(VideoId); }
public int UpdateVideoWithImage(int VideoId, string Title, VideoStatus Status, string Object, string Description, int?CategoryId, int ModifierId, HttpPostedFile Image, bool?AutoResize, bool DeleteOldImage, Languages?lan, bool?Crop) { if (lan == null) { lan = Languages.Default; } var video = GetVideo(VideoId); video.Title = Title; video.Status = (byte)Status; video.Object = Object; video.Description = Description; video.CategoryId = CategoryId; video.DateModified = DateTime.Now; video.UniqueName = StringUtils.ToURL(Title); video.ModifierId = ModifierId; video.Language = (short)lan; MediaData.SubmitChanges(); string path = WebContext.Server.MapPath(Path.Combine(WebContext.StartDir, Folders.VideoThumbsFolder)); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var oldImage = video.ThumbImage; DeleteOldImage = DeleteOldImage || (Image != null && Image.ContentLength > 0); if (DeleteOldImage && !StringUtils.IsNullOrWhiteSpace(video.ThumbImage)) { if (File.Exists(Path.Combine(path, oldImage))) { File.Delete(Path.Combine(path, oldImage)); } video.ThumbImage = ""; } if (Image != null && Image.ContentLength > 0) { string ImageName = Path.GetFileNameWithoutExtension(Image.FileName); ImageName = string.Format("{0}_{1}{2}", ImageName, video.VideoId, Path.GetExtension(Image.FileName)); string _path = Path.Combine(path, ImageName); Image.SaveAs(_path); if (AutoResize != null && AutoResize.Value) { VideoCategory cat = GetVideoCategory(CategoryId.Value); if (cat.ThumbWidth > 0 && cat.ThumbHeight > 0) { if (Crop != null && Crop == true) { ImageUtils.CropImage(_path, _path, (int)cat.ThumbWidth, (int)cat.ThumbHeight, ImageUtils.AnchorPosition.Default); } else { ImageUtils.Resize(_path, _path, (int)cat.ThumbWidth, (int)cat.ThumbHeight); } } else { Config cfg = new Config(); Dimension dim = new Dimension(cfg.GetKey(lw.CTE.parameters.VideoThumbSize)); if (dim.Width > 0 && dim.Height > 0) { ImageUtils.CropImage(_path, _path, (int)dim.Width, (int)dim.Height, ImageUtils.AnchorPosition.Default); } } } video.ThumbImage = ImageName; } MediaData.SubmitChanges(); return(VideoId); }
public int AddVideo(string Title, VideoStatus Status, string Object, string Description, int?CategoryId, int?CreatorId, HttpPostedFile Image, bool?AutoResize, Languages?lan, HttpPostedFile VideoFile) { if (StringUtils.IsNullOrWhiteSpace(Title)) { return(-1); } if (lan == null) { lan = Languages.Default; } Video video = new Video { Title = Title, Status = (byte)Status, Object = Object, Description = Description, CategoryId = CategoryId, CreatorId = CreatorId.Value, DateCreated = DateTime.Now, DateModified = DateTime.Now, UniqueName = StringUtils.ToURL(Title), ModifierId = CreatorId, Language = (short)lan }; MediaData.Videos.InsertOnSubmit(video); MediaData.SubmitChanges(); bool generateThumb = Image != null && Image.ContentLength > 0; if (VideoFile != null && VideoFile.ContentLength > 0) { string videoName = Path.GetFileNameWithoutExtension(VideoFile.FileName); videoName = string.Format("{0}_{1}{2}", videoName, video.VideoId, Path.GetExtension(VideoFile.FileName)); string path = WebContext.Server.MapPath("~/" + Folders.VideosFolder); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = Path.Combine(path, videoName); VideoFile.SaveAs(path); //ShellFile so = ShellFile.FromFilePath(path); //decimal nanoseconds; //decimal.TryParse(so.Properties.System.Media.Duration.Value.ToString(), out nanoseconds); //decimal seconds = nanoseconds * (decimal)0.0000001; //video.VideoLength = seconds; //if (!generateThumb) //{ // string imageName = Path.GetFileNameWithoutExtension(videoName) + ".Jpg"; // string thumbImagePath = WebContext.Server.MapPath("~/" + Folders.VideoThumbsFolder); // if (!Directory.Exists(thumbImagePath)) // { // Directory.CreateDirectory(thumbImagePath); // } // string imagePath = Path.Combine(thumbImagePath, imageName); // //so.Thumbnail.Bitmap.Save (imagePath); // System.Drawing.Bitmap image; // //force the actual thumbnail, not the icon // //so.Thumbnail.FormatOption = ShellThumbnailFormatOptions.ThumbnailOnly; // //image = so.Thumbnail.ExtraLargeBitmap; // image.Save(imagePath); // VideoCategory cat = GetVideoCategory(CategoryId.Value); // if (cat.ThumbWidth > 0 && cat.ThumbHeight > 0) // { // ImageUtils.CropImage(imagePath, imagePath, (int)cat.ThumbWidth, (int)cat.ThumbHeight, ImageUtils.AnchorPosition.Default); // } // else // { // Config cfg = new Config(); // Dimension dim = new Dimension(cfg.GetKey(lw.CTE.parameters.VideoThumbSize)); // if (dim.Width > 0 && dim.Height > 0) // { // ImageUtils.CropImage(imagePath, imagePath, (int)dim.Width, (int)dim.Height, ImageUtils.AnchorPosition.Default); // } // } // video.ThumbImage = imageName; //} video.VideoFile = videoName; MediaData.SubmitChanges(); } if (Image != null && Image.ContentLength > 0) { string ImageName = Path.GetFileNameWithoutExtension(Image.FileName); ImageName = string.Format("{0}_{1}{2}", ImageName, video.VideoId, Path.GetExtension(Image.FileName)); string path = WebContext.Server.MapPath("~/" + Folders.VideoThumbsFolder); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = Path.Combine(path, ImageName); Image.SaveAs(path); if (AutoResize != null && AutoResize.Value == true) { VideoCategory cat = GetVideoCategory(CategoryId.Value); if (cat.ThumbWidth > 0 && cat.ThumbHeight > 0) { //ImageUtils.Resize(path, path, (int)cat.ThumbWidth, (int)cat.ThumbHeight); ImageUtils.CropImage(path, path, (int)cat.ThumbWidth, (int)cat.ThumbHeight, ImageUtils.AnchorPosition.Default); } else { Config cfg = new Config(); Dimension dim = new Dimension(cfg.GetKey(lw.CTE.parameters.VideoThumbSize)); if (dim.Width > 0 && dim.Height > 0) { ImageUtils.CropImage(path, path, (int)dim.Width, (int)dim.Height, ImageUtils.AnchorPosition.Default); } } } video.ThumbImage = ImageName; MediaData.SubmitChanges(); } return(video.VideoId); }
private void RemoveInvalidCustomAttributes() { bool update = false; Database db = this.DatabaseManager.AdomdDatabase; // get the Store dimension Dimension dim = db.Dimensions.FindByName(this.DimensionName); if (dim == null) { throw new Exception("Dimension not found: " + this.DimensionName); } // get existing custom columns DataTable dataColumns = GetCustomDataSourceColumns(); // check and remove for (int i = dim.Attributes.Count - 1; i >= 0; i--) { DimensionAttribute attr = dim.Attributes[i]; // custom attribute consists of 1 column if (attr.KeyColumns.Count != 1) { continue; } // get key column info DataItem di = attr.KeyColumns[0]; string tableId = ((ColumnBinding)di.Source).TableID; string colName = ((ColumnBinding)di.Source).ColumnID; // check if it's not custom if (!colName.StartsWith("GRP@#@")) { continue; } // check if valid if (dataColumns.Rows.Find(colName) != null) { continue; } // remove datasourceview column if (db.DataSourceViews[0].Schema.Tables[tableId].Columns.Contains(colName)) { db.DataSourceViews[0].Schema.Tables[tableId].Columns.Remove(colName); update = true; } // remove hierarchies that contain this attribute for (int j = dim.Hierarchies.Count - 1; j >= 0; j--) { foreach (Level lev in dim.Hierarchies[j].Levels) { if (lev.SourceAttribute == attr) { dim.Hierarchies.RemoveAt(j); update = true; break; // level loop } } } // remove attribute if (dim.Attributes.Contains(attr)) { dim.Attributes.RemoveAt(i); update = true; } } if (update) { // update datasource db.DataSourceViews[0].Update(UpdateOptions.ExpandFull | UpdateOptions.AlterDependents); // update dimension dim.Update(UpdateOptions.ExpandFull | UpdateOptions.AlterDependents); } }
private void CreateCustomAttribute(string colName) { bool update = false; Database db = this.DatabaseManager.AdomdDatabase; // get captions string caption = BuildCaptionFromColumnName(colName); if (caption == null || caption.Length == 0) { return; } string attrCaption = caption + " Attr"; string hierName = caption; // get the dimension Dimension dim = db.Dimensions.FindByName(this.DimensionName); if (dim == null) { throw new Exception("Dimension not found: " + this.DimensionName); } // get key column info DataItem di = dim.KeyAttribute.KeyColumns[0]; string tableId = ((ColumnBinding)di.Source).TableID; // change datasource if (!db.DataSourceViews[0].Schema.Tables[tableId].Columns.Contains(colName)) { db.DataSourceViews[0].Schema.Tables[tableId].Columns.Add(colName, typeof(string)); db.DataSourceViews[0].Update(UpdateOptions.ExpandFull | UpdateOptions.AlterDependents); } // find or create attribute DimensionAttribute attr = dim.Attributes.FindByName(attrCaption); if (attr == null) { attr = dim.Attributes.Add(attrCaption); attr.Usage = AttributeUsage.Regular; attr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], tableId, colName)); attr.NameColumn = CreateDataItem(db.DataSourceViews[0], tableId, colName); attr.AttributeHierarchyVisible = false; attr.MemberNamesUnique = false; update = true; } // find or create hiearachy Hierarchy hier = dim.Hierarchies.FindByName(hierName); if (hier == null) { hier = dim.Hierarchies.Add(hierName); hier.MemberKeysUnique = MemberKeysUnique.NotUnique; hier.Levels.Add(attrCaption.Replace(" Attr", "")).SourceAttributeID = attr.ID; // level to add if (!string.IsNullOrEmpty(this.LevelToAdd) && this.LevelToAdd != dim.KeyAttribute.Name.Replace(" Attr", "")) { DimensionAttribute levelAttr = dim.Attributes.FindByName(this.LevelToAdd + " Attr"); hier.Levels.Add(this.LevelToAdd).SourceAttributeID = levelAttr.ID; } hier.Levels.Add(dim.KeyAttribute.Name.Replace(" Attr", "")).SourceAttributeID = dim.KeyAttribute.ID; update = true; } // update if (update) { dim.Update(UpdateOptions.ExpandFull | UpdateOptions.AlterDependents); } }
public void setSizeConstraints(Dimension minSize, Dimension maxSize) { this.minSize = minSize; this.maxSize = maxSize; }
public Dimension(Dimension d) { x = d.x; y = d.y; }
/// <summary> /// Creates a new <see cref="StatisticItem"/>, to be displayed inside a <see cref="StatisticRow"/> in the results screen. /// </summary> /// <param name="name">The name of the item. Can be <see cref="string.Empty"/> to hide the item header.</param> /// <param name="createContent">A function returning the <see cref="Drawable"/> content to be displayed.</param> /// <param name="requiresHitEvents">Whether this item requires hit events. If true, <see cref="CreateContent"/> will not be called if no hit events are available.</param> /// <param name="dimension">The <see cref="Dimension"/> of this item. This can be thought of as the column dimension of an encompassing <see cref="GridContainer"/>.</param> public StatisticItem([NotNull] string name, [NotNull] Func <Drawable> createContent, bool requiresHitEvents = false, [CanBeNull] Dimension dimension = null) { Name = name; RequiresHitEvents = requiresHitEvents; CreateContent = createContent; Dimension = dimension; }
public override Level GetDimension(Level level, Dimension dimension) { return(null); }
private object analizarNodo(ParseTreeNode actual) { //INICIO DE LA GRAMATICA if (compararNodo(actual, "S")) { LinkedList <Instruccion> instrucciones = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[0]); return(new AST(instrucciones)); } else if (compararNodo(actual, "P")) { LinkedList <Instruccion> pilatemp = new LinkedList <Instruccion>(); if (actual.ChildNodes.Count == 4) { //MAIN Bloque bloque = (Bloque)analizarNodo(actual.ChildNodes[3]); recorrerBloque(pilatemp, bloque); } else if (actual.ChildNodes.Count == 5) { //L_AC; MAIN LinkedList <Bloque> bloques = ((LinkedList <Bloque>)analizarNodo(actual.ChildNodes[3])); //L_AC foreach (Bloque bloque in bloques) { recorrerBloque(pilatemp, bloque); //Agrego las instrucciones que viene en pilatemp } recorrerBloque(pilatemp, (Bloque)analizarNodo(actual.ChildNodes[4])); //MAIN } return(pilatemp); } else if (compararNodo(actual, "L_AC")) { LinkedList <Bloque> acciones = new LinkedList <Bloque>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { acciones.AddLast((Bloque)analizarNodo(hijo)); //AC } return(acciones); } else if (compararNodo(actual, "AC")) { return(analizarNodo(actual.ChildNodes[0])); //retornando Bloque } else if (compararNodo(actual, "G_CNT")) { return(new Bloque((LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[1]))); } else if (compararNodo(actual, "L_CNT")) { LinkedList <Instruccion> constantes = new LinkedList <Instruccion>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { constantes.AddLast((Instruccion)analizarNodo(hijo)); } return(constantes); } else if (compararNodo(actual, "CNT")) { string id = getLexema(actual.ChildNodes[0]); Expresion value = (Expresion)analizarNodo(actual.ChildNodes[2]); return(new DeclaConstante(id, value, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "G_TY")) { return(new Bloque((LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[1]))); } else if (compararNodo(actual, "L_TY")) { LinkedList <Instruccion> instrucciones = new LinkedList <Instruccion>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { instrucciones.AddLast((Instruccion)analizarNodo(hijo)); } return(instrucciones); } else if (compararNodo(actual, "TY")) { string id = getLexema(actual.ChildNodes[0]); if (compararNodo(actual.ChildNodes[2].ChildNodes[0], "OBJ")) { LinkedList <Param> paramList = (LinkedList <Param>)analizarNodo(actual.ChildNodes[2].ChildNodes[0]); //OBJ return(new StructSt(id, paramList, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else //ARRAY { LinkedList <Dimension> dimensiones = (LinkedList <Dimension>)analizarNodo(actual.ChildNodes[2].ChildNodes[0].ChildNodes[2]); //L_DIM Tipo tipoArreglo = (Tipo)analizarNodo(actual.ChildNodes[2].ChildNodes[0].ChildNodes[5]); //ZTIPO return(new ArraySt(id, dimensiones, tipoArreglo, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } } else if (compararNodo(actual, "L_DIM")) { LinkedList <Dimension> dimensiones = new LinkedList <Dimension>(); int numero = 0; foreach (ParseTreeNode hijo in actual.ChildNodes) { Dimension dimension = (Dimension)analizarNodo(hijo); numero++; dimension.numero = numero; dimensiones.AddLast(dimension); } return(dimensiones); } else if (compararNodo(actual, "DIM")) { Primitivo inferior = (Primitivo)obtenerLiteral(actual.ChildNodes[0]); Primitivo superior = (Primitivo)obtenerLiteral(actual.ChildNodes[3]); return(new Dimension(inferior, superior)); } else if (compararNodo(actual, "OBJ")) { return(analizarNodo(actual.ChildNodes[2])); } else if (compararNodo(actual, "L_AT")) { LinkedList <Param> paramList = new LinkedList <Param>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { LinkedList <Param> paramhijos = (LinkedList <Param>)analizarNodo(hijo); foreach (Param paramhijo in paramhijos) { paramList.AddLast(paramhijo); } } return(paramList); } else if (compararNodo(actual, "AT")) { LinkedList <string> idList = (LinkedList <string>)analizarNodo(actual.ChildNodes[0]); //L_ID Tipo tipo = (Tipo)analizarNodo(actual.ChildNodes[2]); //ZTIPO LinkedList <Param> atributos = new LinkedList <Param>(); foreach (string id in idList) { atributos.AddLast(new Param(id, tipo)); } return(atributos); } else if (compararNodo(actual, "DECLAS")) { return(new Bloque((LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[1]))); } else if (compararNodo(actual, "L_VR")) { LinkedList <Instruccion> declaraciones = new LinkedList <Instruccion>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { declaraciones.AddLast((Instruccion)analizarNodo(hijo)); } return(declaraciones); } else if (compararNodo(actual, "VR")) { LinkedList <string> idList; Tipo tipo; if (actual.ChildNodes.Count == 6) { idList = (LinkedList <string>)analizarNodo(actual.ChildNodes[0]); tipo = (Tipo)analizarNodo(actual.ChildNodes[2]); Expresion value = (Expresion)analizarNodo(actual.ChildNodes[4]); return(new Declaracion(tipo, idList, value, actual.ChildNodes[1].Token.Location.Line, actual.ChildNodes[1].Token.Location.Column)); } else //4 HIJOS { idList = (LinkedList <string>)analizarNodo(actual.ChildNodes[0]); tipo = (Tipo)analizarNodo(actual.ChildNodes[2]); Expresion value = null; if (tipo.tipo == Tipos.STRUCT) { value = new NewStruct(tipo.tipoId, actual.ChildNodes[1].Token.Location.Line, actual.ChildNodes[1].Token.Location.Column); } return(new Declaracion(tipo, idList, value, actual.ChildNodes[1].Token.Location.Line, actual.ChildNodes[1].Token.Location.Column)); } } else if (compararNodo(actual, "L_ID")) { LinkedList <string> idList = new LinkedList <string>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { idList.AddLast(getLexema(hijo)); } return(idList); } else if (compararNodo(actual, "ZTIPO")) { Tipos tipoenum; if (compararID(actual.ChildNodes[0])) { tipoenum = Tipo.Tipos.STRUCT; return(new Tipo(tipoenum, getLexema(actual.ChildNodes[0]))); } else //TIPO { tipoenum = (Tipos)analizarNodo(actual.ChildNodes[0]); return(new Tipo(tipoenum)); } } else if (compararNodo(actual, "TIPO")) { string tipocadena = getLexema(actual.ChildNodes[0]).ToLower(); switch (tipocadena) { case "integer": return(Tipos.INTEGER); case "real": return(Tipos.REAL); case "string": return(Tipos.STRING); default: return(Tipos.BOOLEAN); //boolean } } else if (compararNodo(actual, "L_PROF")) { LinkedList <Instruccion> funciones = new LinkedList <Instruccion>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { funciones.AddLast((Instruccion)analizarNodo(hijo)); } return(new Bloque(funciones)); } else if (compararNodo(actual, "PROF")) { return(analizarNodo(actual.ChildNodes[0])); } else if (compararNodo(actual, "PRO")) { Tipo tipo = new Tipo(Tipo.Tipos.VOID); string id = getLexema(actual.ChildNodes[1]); LinkedList <Param> parametros = new LinkedList <Param>(); LinkedList <Bloque> bloques; if (actual.ChildNodes.Count == 7) { parametros = (LinkedList <Param>)analizarNodo(actual.ChildNodes[3]); bloques = (LinkedList <Bloque>)analizarNodo(actual.ChildNodes[6]); } else if (actual.ChildNodes.Count == 6) { bloques = (LinkedList <Bloque>)analizarNodo(actual.ChildNodes[5]); } else //4 hijos { bloques = (LinkedList <Bloque>)analizarNodo(actual.ChildNodes[3]); } return(new FunctionSt(tipo, id, parametros, bloques, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "FUN")) { string id = getLexema(actual.ChildNodes[1]); Tipo tipo; LinkedList <Param> parametros = new LinkedList <Param>(); LinkedList <Bloque> bloques; if (actual.ChildNodes.Count == 9) { parametros = (LinkedList <Param>)analizarNodo(actual.ChildNodes[3]); tipo = (Tipo)analizarNodo(actual.ChildNodes[6]); bloques = (LinkedList <Bloque>)analizarNodo(actual.ChildNodes[8]); } else if (actual.ChildNodes.Count == 8) { tipo = (Tipo)analizarNodo(actual.ChildNodes[5]); bloques = (LinkedList <Bloque>)analizarNodo(actual.ChildNodes[7]); } else //6 hijos { tipo = (Tipo)analizarNodo(actual.ChildNodes[3]); bloques = (LinkedList <Bloque>)analizarNodo(actual.ChildNodes[5]); } return(new FunctionSt(tipo, id, parametros, bloques, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "L_PARAM")) { LinkedList <Param> parametros = new LinkedList <Param>(); LinkedList <Param> paramhijos; foreach (ParseTreeNode hijo in actual.ChildNodes) { paramhijos = (LinkedList <Param>)analizarNodo(hijo); foreach (Param param in paramhijos) { parametros.AddLast(param); } } return(parametros); } else if (compararNodo(actual, "PARAM")) { LinkedList <string> idList; Tipo tipo; bool isRef; if (actual.ChildNodes.Count == 3) { idList = (LinkedList <string>)analizarNodo(actual.ChildNodes[0]); tipo = (Tipo)analizarNodo(actual.ChildNodes[2]); //ZTIPO isRef = false; } else //4 HIJOS { idList = (LinkedList <string>)analizarNodo(actual.ChildNodes[1]); tipo = (Tipo)analizarNodo(actual.ChildNodes[3]); //ZTIPO isRef = true; } LinkedList <Param> atributos = new LinkedList <Param>(); foreach (string id in idList) { atributos.AddLast(new Param(id, tipo, isRef)); } return(atributos); } else if (compararNodo(actual, "SPACE")) { LinkedList <Bloque> bloques; Bloque nuevobloque; LinkedList <Instruccion> sentencias; if (actual.ChildNodes.Count == 1) //BEG { bloques = new LinkedList <Bloque>(); sentencias = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[0]); nuevobloque = new Bloque(sentencias); bloques.AddLast(nuevobloque); } else //L_DEF BEG { bloques = (LinkedList <Bloque>)analizarNodo(actual.ChildNodes[0]); sentencias = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[1]); nuevobloque = new Bloque(sentencias); bloques.AddLast(nuevobloque); } return(bloques); } else if (compararNodo(actual, "L_DEF")) { LinkedList <Bloque> bloques = new LinkedList <Bloque>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { bloques.AddLast((Bloque)analizarNodo(hijo)); } return(bloques); } else if (compararNodo(actual, "DEF")) { //retorno un bloque return(analizarNodo(actual.ChildNodes[0])); } else if (compararNodo(actual, "MAIN")) { //L_SEN return(new Bloque((LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[1]))); } else if (compararNodo(actual, "L_SEN")) { LinkedList <Instruccion> sentencias = new LinkedList <Instruccion>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { sentencias.AddLast((Instruccion)analizarNodo(hijo)); //SEN } return(sentencias); } else if (compararNodo(actual, "SEN")) { return(analizarNodo(actual.ChildNodes[0])); } else if (compararNodo(actual, "BEG")) { return(analizarNodo(actual.ChildNodes[1])); //retorna lista de sentencias } else if (compararNodo(actual, "L_SENCU")) { LinkedList <Instruccion> sentencias = new LinkedList <Instruccion>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { LinkedList <Instruccion> sentenciashijo = (LinkedList <Instruccion>)analizarNodo(hijo); foreach (Instruccion senhijo in sentenciashijo) { sentencias.AddLast(senhijo); } } return(sentencias); } else if (compararNodo(actual, "SENCU")) { LinkedList <Instruccion> sentencias; if (compararNodo(actual.ChildNodes[0], "BEG")) { sentencias = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[0]); } else //SEN { sentencias = new LinkedList <Instruccion>(); sentencias.AddLast((Instruccion)analizarNodo(actual.ChildNodes[0])); } return(sentencias); } else if (compararNodo(actual, "ASIG")) { Expresion target = (Expresion)analizarNodo(actual.ChildNodes[0]); Expresion value = (Expresion)analizarNodo(actual.ChildNodes[2]); return(new Asignacion(target, value, actual.ChildNodes[1].Token.Location.Line, actual.ChildNodes[1].Token.Location.Column)); } else if (compararNodo(actual, "ASID")) { if (actual.ChildNodes.Count == 3) { Expresion anterior = (Expresion)analizarNodo(actual.ChildNodes[0]); string id = getLexema(actual.ChildNodes[2]); return(new AsignacionId(id, anterior, actual.ChildNodes[1].Token.Location.Line, actual.ChildNodes[1].Token.Location.Column)); } else //UN HIJO { string id = getLexema(actual.ChildNodes[0]); return(new AsignacionId(id, null, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } } else if (compararNodo(actual, "IF")) { Expresion condicion = (Expresion)analizarNodo(actual.ChildNodes[1]); LinkedList <Instruccion> sentencias = new LinkedList <Instruccion>(); LinkedList <Instruccion> sentenciasElse; if (actual.ChildNodes.Count <= 5) { if (compararNodo(actual.ChildNodes[3], "BEG")) { sentencias = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[3]); } else //SEN { sentencias.AddLast((Instruccion)analizarNodo(actual.ChildNodes[3])); } sentenciasElse = null; if (actual.ChildNodes.Count == 5) { sentenciasElse = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[4]); //ELSE } } else //7 HIJOS { sentencias = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[4]); sentenciasElse = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[6]); } return(new If(condicion, sentencias, sentenciasElse, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "ELSE")) { LinkedList <Instruccion> sentencias; if (compararNodo(actual.ChildNodes[1], "BEG")) { sentencias = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[1]); } else //SEN { sentencias = new LinkedList <Instruccion>(); sentencias.AddLast((Instruccion)analizarNodo(actual.ChildNodes[1])); } return(sentencias); } else if (compararNodo(actual, "CASE")) { string id; AccessId variable; LinkedList <Opcion> opciones; LinkedList <Instruccion> sentenciasElse = null; if (actual.ChildNodes.Count == 6) { id = getLexema(actual.ChildNodes[1]); variable = new AccessId(id, null, actual.ChildNodes[1].Token.Location.Line, actual.ChildNodes[1].Token.Location.Column); opciones = (LinkedList <Opcion>)analizarNodo(actual.ChildNodes[3]); } else if (actual.ChildNodes.Count == 7) { id = getLexema(actual.ChildNodes[1]); variable = new AccessId(id, null, actual.ChildNodes[1].Token.Location.Line, actual.ChildNodes[1].Token.Location.Column); opciones = (LinkedList <Opcion>)analizarNodo(actual.ChildNodes[3]); sentenciasElse = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[4]); } else if (actual.ChildNodes.Count == 8) { id = getLexema(actual.ChildNodes[2]); variable = new AccessId(id, null, actual.ChildNodes[2].Token.Location.Line, actual.ChildNodes[2].Token.Location.Column); opciones = (LinkedList <Opcion>)analizarNodo(actual.ChildNodes[5]); } else // 9 HIJOS { id = getLexema(actual.ChildNodes[2]); variable = new AccessId(id, null, actual.ChildNodes[2].Token.Location.Line, actual.ChildNodes[2].Token.Location.Column); opciones = (LinkedList <Opcion>)analizarNodo(actual.ChildNodes[5]); sentenciasElse = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[6]); } return(new Case(variable, opciones, sentenciasElse, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "L_OPC")) { LinkedList <Opcion> opciones = new LinkedList <Opcion>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { opciones.AddLast((Opcion)analizarNodo(hijo)); } return(opciones); } else if (compararNodo(actual, "OPC")) { LinkedList <Expresion> etiquetas = (LinkedList <Expresion>)analizarNodo(actual.ChildNodes[0]); LinkedList <Instruccion> sentencias = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[2]); return(new Opcion(etiquetas, sentencias, actual.ChildNodes[1].Token.Location.Line, actual.ChildNodes[1].Token.Location.Column)); } else if (compararNodo(actual, "LETC")) { LinkedList <Expresion> etiquetas = new LinkedList <Expresion>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { etiquetas.AddLast((Expresion)analizarNodo(hijo)); } return(etiquetas); } else if (compararNodo(actual, "ETC")) { if (actual.ChildNodes.Count == 2) { Primitivo numero = (Primitivo)obtenerLiteral(actual.ChildNodes[1]); numero.value = "-" + numero.value.ToString(); return(numero); } else { return(obtenerLiteral(actual.ChildNodes[0])); } } else if (compararNodo(actual, "REP")) { LinkedList <Instruccion> sentencias = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[1]); Expresion condicion = (Expresion)analizarNodo(actual.ChildNodes[3]); return(new Repeat(condicion, sentencias, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "WH")) { Expresion condicion = (Expresion)analizarNodo(actual.ChildNodes[1]); LinkedList <Instruccion> sentencias = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[3]); return(new While(condicion, sentencias, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "FOR")) { string id = getLexema(actual.ChildNodes[1]); Expresion primero = (Expresion)analizarNodo(actual.ChildNodes[3]); string fad = getLexema(actual.ChildNodes[4].ChildNodes[0]); Expresion segundo = (Expresion)analizarNodo(actual.ChildNodes[5]); LinkedList <Instruccion> sentencias = (LinkedList <Instruccion>)analizarNodo(actual.ChildNodes[7]); return(new For(id, primero, fad, segundo, sentencias, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "BRK")) { return(new Break(actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "COT")) { return(new Continue(actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "WRT")) { bool esSalto = false; if (getLexema(actual.ChildNodes[0]).ToLower() == "writeln") { esSalto = true; //sino es write } return(new Writeln((LinkedList <Expresion>)analizarNodo(actual.ChildNodes[2]), esSalto, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararNodo(actual, "EXT")) { if (actual.ChildNodes.Count == 5) { return(new Return((Expresion)analizarNodo(actual.ChildNodes[2]), actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else // 4 HIJOS { return(new Return(null, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } } else if (compararNodo(actual, "L_EXP")) { LinkedList <Expresion> expresiones = new LinkedList <Expresion>(); foreach (ParseTreeNode hijo in actual.ChildNodes) { expresiones.AddLast((Expresion)analizarNodo(hijo)); } return(expresiones); } else if (compararNodo(actual, "EXPLOG")) { if (actual.ChildNodes.Count == 3) { if (compararNodo(actual.ChildNodes[0], "(")) // ( EXPLOG ) { return(analizarNodo(actual.ChildNodes[1])); } else { //EXPLOG SIGNO EXPLOG Expresion izquierda = (Expresion)analizarNodo(actual.ChildNodes[0]); Expresion derecha = (Expresion)analizarNodo(actual.ChildNodes[2]); return(getOperacion(actual.ChildNodes[1], izquierda, derecha)); } } else if (actual.ChildNodes.Count == 2) { //not EXPLOG return(new Not((Expresion)analizarNodo(actual.ChildNodes[1]), actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } if (actual.ChildNodes.Count == 1) { //UN HIJO return(analizarNodo(actual.ChildNodes[0])); } } else if (compararNodo(actual, "EXPRELA")) { if (actual.ChildNodes.Count == 3) { if (compararNodo(actual.ChildNodes[0], "(")) // ( EXPRELA ) { return(analizarNodo(actual.ChildNodes[1])); } else { //EXPRELA SIGNO EXPRELA Expresion izquierda = (Expresion)analizarNodo(actual.ChildNodes[0]); Expresion derecha = (Expresion)analizarNodo(actual.ChildNodes[2]); return(getOperacion(actual.ChildNodes[1], izquierda, derecha)); } } else //UN HIJO { return(analizarNodo(actual.ChildNodes[0])); } } else if (compararNodo(actual, "EXPNUMERICA")) { if (actual.ChildNodes.Count == 3) { if (compararNodo(actual.ChildNodes[0], "(")) // ( EXPNUMERICA ) { return(analizarNodo(actual.ChildNodes[1])); } else { //EXPNUMERICA operador EXPNUMERICA Expresion izquierda = (Expresion)analizarNodo(actual.ChildNodes[0]); Expresion derecha = (Expresion)analizarNodo(actual.ChildNodes[2]); return(getOperacion(actual.ChildNodes[1], izquierda, derecha)); } } else if (actual.ChildNodes.Count == 2) { Expresion unario = (Expresion)analizarNodo(actual.ChildNodes[1]); return(new RestaUni(unario, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else //UN HIJO { if (compararID(actual.ChildNodes[0])) { } else { return(analizarNodo(actual.ChildNodes[0])); //LITERAL o ACCESS } } } else if (compararNodo(actual, "ACCESS")) { return(analizarNodo(actual.ChildNodes[0])); } else if (compararNodo(actual, "ACCID")) { if (actual.ChildNodes.Count == 3) { Expresion anterior = (Expresion)analizarNodo(actual.ChildNodes[0]); string id = getLexema(actual.ChildNodes[2]); return(new AccessId(id, anterior, actual.ChildNodes[1].Token.Location.Line, actual.ChildNodes[1].Token.Location.Column)); } else //UN HIJO { string id = getLexema(actual.ChildNodes[0]); return(new AccessId(id, null, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } } else if (compararNodo(actual, "CALL")) { string id = getLexema(actual.ChildNodes[0]); LinkedList <Expresion> parametros = new LinkedList <Expresion>(); if (actual.ChildNodes.Count == 5) { parametros = (LinkedList <Expresion>)analizarNodo(actual.ChildNodes[2]); } return(new AsignacionFunc(id, parametros, null, actual.ChildNodes[0].Token.Location.Line, actual.ChildNodes[0].Token.Location.Column)); } else if (compararLiteral(actual)) //LITERAL { return(obtenerLiteral(actual)); } return(null); }
public static DxfDocument Test(string file, string output = null) { // optionally you can save the information to a text file bool outputLog = !string.IsNullOrEmpty(output); TextWriter writer = null; if (outputLog) { writer = new StreamWriter(File.Create(output)); Console.SetOut(writer); } // check if the dxf actually exists FileInfo fileInfo = new FileInfo(file); if (!fileInfo.Exists) { Console.WriteLine("THE FILE {0} DOES NOT EXIST", file); Console.WriteLine(); if (outputLog) { writer.Flush(); writer.Close(); } else { Console.WriteLine("Press a key to continue..."); Console.ReadLine(); } return(null); } bool isBinary; DxfVersion dxfVersion = DxfDocument.CheckDxfFileVersion(file, out isBinary); // check if the file is a dxf if (dxfVersion == DxfVersion.Unknown) { Console.WriteLine("THE FILE {0} IS NOT A VALID DXF OR THE DXF DOES NOT INCLUDE VERSION INFORMATION IN THE HEADER SECTION", file); Console.WriteLine(); if (outputLog) { writer.Flush(); writer.Close(); } else { Console.WriteLine("Press a key to continue..."); Console.ReadLine(); } return(null); } // check if the dxf file version is supported if (dxfVersion < DxfVersion.AutoCad2000) { Console.WriteLine("THE FILE {0} IS NOT A SUPPORTED DXF", file); Console.WriteLine(); Console.WriteLine("FILE VERSION: {0}", dxfVersion); Console.WriteLine(); if (outputLog) { writer.Flush(); writer.Close(); } else { Console.WriteLine("Press a key to continue..."); Console.ReadLine(); } return(null); } // DxfDocument dxf = DxfDocument.Load(file, new List<string> { @".\Support" }); DxfDocument dxf = DxfDocument.Load(file); // check if there has been any problems loading the file, // this might be the case of a corrupt file or a problem in the library if (dxf == null) { Console.WriteLine("ERROR LOADING {0}", file); Console.WriteLine(); Console.WriteLine("Press a key to continue..."); Console.ReadLine(); if (outputLog) { writer.Flush(); writer.Close(); } else { Console.WriteLine("Press a key to continue..."); Console.ReadLine(); } return(null); } // the dxf has been properly loaded, let's show some information about it Console.WriteLine("FILE NAME: {0}", file); Console.WriteLine("\tbinary dxf: {0}", isBinary); Console.WriteLine(); Console.WriteLine("FILE VERSION: {0}", dxf.DrawingVariables.AcadVer); Console.WriteLine(); Console.WriteLine("FILE COMMENTS: {0}", dxf.Comments.Count); foreach (var o in dxf.Comments) { Console.WriteLine("\t{0}", o); } Console.WriteLine(); Console.WriteLine("FILE TIME:"); Console.WriteLine("\tdrawing created (UTC): {0}.{1}", dxf.DrawingVariables.TduCreate, dxf.DrawingVariables.TduCreate.Millisecond.ToString("000")); Console.WriteLine("\tdrawing last update (UTC): {0}.{1}", dxf.DrawingVariables.TduUpdate, dxf.DrawingVariables.TduUpdate.Millisecond.ToString("000")); Console.WriteLine("\tdrawing edition time: {0}", dxf.DrawingVariables.TdinDwg); Console.WriteLine(); Console.WriteLine("APPLICATION REGISTRIES: {0}", dxf.ApplicationRegistries.Count); foreach (var o in dxf.ApplicationRegistries) { Console.WriteLine("\t{0}; References count: {1}", o.Name, dxf.ApplicationRegistries.GetReferences(o.Name).Count); } Console.WriteLine(); Console.WriteLine("LAYERS: {0}", dxf.Layers.Count); foreach (var o in dxf.Layers) { Console.WriteLine("\t{0}; References count: {1}", o.Name, dxf.Layers.GetReferences(o).Count); Debug.Assert(ReferenceEquals(o.Linetype, dxf.Linetypes[o.Linetype.Name]), "Object reference not equal."); } Console.WriteLine(); Console.WriteLine("LINE TYPES: {0}", dxf.Linetypes.Count); foreach (var o in dxf.Linetypes) { Console.WriteLine("\t{0}; References count: {1}", o.Name, dxf.Linetypes.GetReferences(o.Name).Count); } Console.WriteLine(); Console.WriteLine("TEXT STYLES: {0}", dxf.TextStyles.Count); foreach (var o in dxf.TextStyles) { Console.WriteLine("\t{0}; References count: {1}", o.Name, dxf.TextStyles.GetReferences(o.Name).Count); } Console.WriteLine(); //Console.WriteLine("SHAPE STYLES: {0}", dxf.ShapeStyles.Count); //foreach (var o in dxf.ShapeStyles) //{ // Console.WriteLine("\t{0}; References count: {1}", o.Name, dxf.ShapeStyles.GetReferences(o.Name).Count); //} //Console.WriteLine(); Console.WriteLine("DIMENSION STYLES: {0}", dxf.DimensionStyles.Count); foreach (var o in dxf.DimensionStyles) { Console.WriteLine("\t{0}; References count: {1}", o.Name, dxf.DimensionStyles.GetReferences(o.Name).Count); Debug.Assert(ReferenceEquals(o.TextStyle, dxf.TextStyles[o.TextStyle.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(o.DimLineLinetype, dxf.Linetypes[o.DimLineLinetype.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(o.ExtLine1Linetype, dxf.Linetypes[o.ExtLine1Linetype.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(o.ExtLine2Linetype, dxf.Linetypes[o.ExtLine2Linetype.Name]), "Object reference not equal."); if (o.DimArrow1 != null) { Debug.Assert(ReferenceEquals(o.DimArrow1, dxf.Blocks[o.DimArrow1.Name]), "Object reference not equal."); } if (o.DimArrow2 != null) { Debug.Assert(ReferenceEquals(o.DimArrow2, dxf.Blocks[o.DimArrow2.Name]), "Object reference not equal."); } } Console.WriteLine(); Console.WriteLine("MLINE STYLES: {0}", dxf.MlineStyles.Count); foreach (var o in dxf.MlineStyles) { Console.WriteLine("\t{0}; References count: {1}", o.Name, dxf.MlineStyles.GetReferences(o.Name).Count); foreach (var e in o.Elements) { Debug.Assert(ReferenceEquals(e.Linetype, dxf.Linetypes[e.Linetype.Name]), "Object reference not equal."); } } Console.WriteLine(); Console.WriteLine("UCSs: {0}", dxf.UCSs.Count); foreach (var o in dxf.UCSs) { Console.WriteLine("\t{0}", o.Name); } Console.WriteLine(); Console.WriteLine("BLOCKS: {0}", dxf.Blocks.Count); foreach (var o in dxf.Blocks) { Console.WriteLine("\t{0}; References count: {1}", o.Name, dxf.Blocks.GetReferences(o.Name).Count); Debug.Assert(ReferenceEquals(o.Layer, dxf.Layers[o.Layer.Name]), "Object reference not equal."); foreach (var e in o.Entities) { Debug.Assert(ReferenceEquals(e.Layer, dxf.Layers[e.Layer.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(e.Linetype, dxf.Linetypes[e.Linetype.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(e.Owner, dxf.Blocks[o.Name]), "Object reference not equal."); foreach (var x in e.XData.Values) { Debug.Assert(ReferenceEquals(x.ApplicationRegistry, dxf.ApplicationRegistries[x.ApplicationRegistry.Name]), "Object reference not equal."); } Text txt = e as Text; if (txt != null) { Debug.Assert(ReferenceEquals(txt.Style, dxf.TextStyles[txt.Style.Name]), "Object reference not equal."); } MText mtxt = e as MText; if (mtxt != null) { Debug.Assert(ReferenceEquals(mtxt.Style, dxf.TextStyles[mtxt.Style.Name]), "Object reference not equal."); } Dimension dim = e as Dimension; if (dim != null) { Debug.Assert(ReferenceEquals(dim.Style, dxf.DimensionStyles[dim.Style.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(dim.Block, dxf.Blocks[dim.Block.Name]), "Object reference not equal."); } MLine mline = e as MLine; if (mline != null) { Debug.Assert(ReferenceEquals(mline.Style, dxf.MlineStyles[mline.Style.Name]), "Object reference not equal."); } Image img = e as Image; if (img != null) { Debug.Assert(ReferenceEquals(img.Definition, dxf.ImageDefinitions[img.Definition.Name]), "Object reference not equal."); } Insert ins = e as Insert; if (ins != null) { Debug.Assert(ReferenceEquals(ins.Block, dxf.Blocks[ins.Block.Name]), "Object reference not equal."); foreach (var a in ins.Attributes) { Debug.Assert(ReferenceEquals(a.Layer, dxf.Layers[a.Layer.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(a.Linetype, dxf.Linetypes[a.Linetype.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(a.Style, dxf.TextStyles[a.Style.Name]), "Object reference not equal."); } } } foreach (var a in o.AttributeDefinitions.Values) { Debug.Assert(ReferenceEquals(a.Layer, dxf.Layers[a.Layer.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(a.Linetype, dxf.Linetypes[a.Linetype.Name]), "Object reference not equal."); foreach (var x in a.XData.Values) { Debug.Assert(ReferenceEquals(x.ApplicationRegistry, dxf.ApplicationRegistries[x.ApplicationRegistry.Name]), "Object reference not equal."); } } } Console.WriteLine(); Console.WriteLine("LAYOUTS: {0}", dxf.Layouts.Count); foreach (var o in dxf.Layouts) { Debug.Assert(ReferenceEquals(o.AssociatedBlock, dxf.Blocks[o.AssociatedBlock.Name]), "Object reference not equal."); Console.WriteLine("\t{0}; References count: {1}", o.Name, dxf.Layouts.GetReferences(o.Name).Count); List <DxfObject> entities = dxf.Layouts.GetReferences(o.Name); foreach (var e in entities) { EntityObject entity = e as EntityObject; if (entity != null) { Debug.Assert(ReferenceEquals(entity.Layer, dxf.Layers[entity.Layer.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(entity.Linetype, dxf.Linetypes[entity.Linetype.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(entity.Owner, dxf.Blocks[o.AssociatedBlock.Name]), "Object reference not equal."); foreach (var x in entity.XData.Values) { Debug.Assert(ReferenceEquals(x.ApplicationRegistry, dxf.ApplicationRegistries[x.ApplicationRegistry.Name]), "Object reference not equal."); } } Text txt = e as Text; if (txt != null) { Debug.Assert(ReferenceEquals(txt.Style, dxf.TextStyles[txt.Style.Name]), "Object reference not equal."); } MText mtxt = e as MText; if (mtxt != null) { Debug.Assert(ReferenceEquals(mtxt.Style, dxf.TextStyles[mtxt.Style.Name]), "Object reference not equal."); } Dimension dim = e as Dimension; if (dim != null) { Debug.Assert(ReferenceEquals(dim.Style, dxf.DimensionStyles[dim.Style.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(dim.Block, dxf.Blocks[dim.Block.Name]), "Object reference not equal."); } MLine mline = e as MLine; if (mline != null) { Debug.Assert(ReferenceEquals(mline.Style, dxf.MlineStyles[mline.Style.Name]), "Object reference not equal."); } Image img = e as Image; if (img != null) { Debug.Assert(ReferenceEquals(img.Definition, dxf.ImageDefinitions[img.Definition.Name]), "Object reference not equal."); } Insert ins = e as Insert; if (ins != null) { Debug.Assert(ReferenceEquals(ins.Block, dxf.Blocks[ins.Block.Name]), "Object reference not equal."); foreach (var a in ins.Attributes) { Debug.Assert(ReferenceEquals(a.Layer, dxf.Layers[a.Layer.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(a.Linetype, dxf.Linetypes[a.Linetype.Name]), "Object reference not equal."); Debug.Assert(ReferenceEquals(a.Style, dxf.TextStyles[a.Style.Name]), "Object reference not equal."); } } } } Console.WriteLine(); Console.WriteLine("IMAGE DEFINITIONS: {0}", dxf.ImageDefinitions.Count); foreach (var o in dxf.ImageDefinitions) { Console.WriteLine("\t{0}; File name: {1}; References count: {2}", o.Name, o.FileName, dxf.ImageDefinitions.GetReferences(o.Name).Count); } Console.WriteLine(); Console.WriteLine("DGN UNDERLAY DEFINITIONS: {0}", dxf.UnderlayDgnDefinitions.Count); foreach (var o in dxf.UnderlayDgnDefinitions) { Console.WriteLine("\t{0}; File name: {1}; References count: {2}", o.Name, o.FileName, dxf.UnderlayDgnDefinitions.GetReferences(o.Name).Count); } Console.WriteLine(); Console.WriteLine("DWF UNDERLAY DEFINITIONS: {0}", dxf.UnderlayDwfDefinitions.Count); foreach (var o in dxf.UnderlayDwfDefinitions) { Console.WriteLine("\t{0}; File name: {1}; References count: {2}", o.Name, o.FileName, dxf.UnderlayDwfDefinitions.GetReferences(o.Name).Count); } Console.WriteLine(); Console.WriteLine("PDF UNDERLAY DEFINITIONS: {0}", dxf.UnderlayPdfDefinitions.Count); foreach (var o in dxf.UnderlayPdfDefinitions) { Console.WriteLine("\t{0}; File name: {1}; References count: {2}", o.Name, o.FileName, dxf.UnderlayPdfDefinitions.GetReferences(o.Name).Count); } Console.WriteLine(); Console.WriteLine("GROUPS: {0}", dxf.Groups.Count); foreach (var o in dxf.Groups) { Console.WriteLine("\t{0}; Entities count: {1}", o.Name, o.Entities.Count); } Console.WriteLine(); Console.WriteLine("ATTRIBUTE DEFINITIONS for the \"Model\" Layout: {0}", dxf.Layouts[Layout.ModelSpaceName].AssociatedBlock.AttributeDefinitions.Count); foreach (var o in dxf.Layouts[Layout.ModelSpaceName].AssociatedBlock.AttributeDefinitions) { Console.WriteLine("\tTag: {0}", o.Value.Tag); } Console.WriteLine(); // the entities lists contain the geometry that has a graphical representation in the drawing across all layouts, // to get the entities that belongs to a specific layout you can get the references through the Layouts.GetReferences(name) // or check the EntityObject.Owner.Record.Layout property Console.WriteLine("ENTITIES for the Active Layout = {0}:", dxf.ActiveLayout); Console.WriteLine("\t{0}; count: {1}", EntityType.Arc, dxf.Arcs.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Circle, dxf.Circles.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Dimension, dxf.Dimensions.Count()); foreach (var a in dxf.Dimensions) { foreach (var styleOverride in a.StyleOverrides.Values) { switch (styleOverride.Type) { case DimensionStyleOverrideType.DimLineLinetype: Debug.Assert(ReferenceEquals((Linetype)styleOverride.Value, dxf.Linetypes[((Linetype)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.ExtLine1Linetype: Debug.Assert(ReferenceEquals((Linetype)styleOverride.Value, dxf.Linetypes[((Linetype)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.ExtLine2Linetype: Debug.Assert(ReferenceEquals((Linetype)styleOverride.Value, dxf.Linetypes[((Linetype)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.TextStyle: Debug.Assert(ReferenceEquals((TextStyle)styleOverride.Value, dxf.TextStyles[((TextStyle)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.LeaderArrow: Debug.Assert(ReferenceEquals((Block)styleOverride.Value, dxf.Blocks[((Block)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.DimArrow1: if (styleOverride.Value == null) { break; } Debug.Assert(ReferenceEquals((Block)styleOverride.Value, dxf.Blocks[((Block)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.DimArrow2: if (styleOverride.Value == null) { break; } Debug.Assert(ReferenceEquals((Block)styleOverride.Value, dxf.Blocks[((Block)styleOverride.Value).Name]), "Object reference not equal."); break; } } } Console.WriteLine("\t{0}; count: {1}", EntityType.Ellipse, dxf.Ellipses.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Face3D, dxf.Faces3d.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Hatch, dxf.Hatches.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Image, dxf.Images.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Insert, dxf.Inserts.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Leader, dxf.Leaders.Count()); foreach (var a in dxf.Leaders) { foreach (var styleOverride in a.StyleOverrides.Values) { switch (styleOverride.Type) { case DimensionStyleOverrideType.DimLineLinetype: Debug.Assert(ReferenceEquals((Linetype)styleOverride.Value, dxf.Linetypes[((Linetype)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.ExtLine1Linetype: Debug.Assert(ReferenceEquals((Linetype)styleOverride.Value, dxf.Linetypes[((Linetype)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.ExtLine2Linetype: Debug.Assert(ReferenceEquals((Linetype)styleOverride.Value, dxf.Linetypes[((Linetype)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.TextStyle: Debug.Assert(ReferenceEquals((TextStyle)styleOverride.Value, dxf.TextStyles[((TextStyle)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.LeaderArrow: Debug.Assert(ReferenceEquals((Block)styleOverride.Value, dxf.Blocks[((Block)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.DimArrow1: Debug.Assert(ReferenceEquals((Block)styleOverride.Value, dxf.Blocks[((Block)styleOverride.Value).Name]), "Object reference not equal."); break; case DimensionStyleOverrideType.DimArrow2: Debug.Assert(ReferenceEquals((Block)styleOverride.Value, dxf.Blocks[((Block)styleOverride.Value).Name]), "Object reference not equal."); break; } } } Console.WriteLine("\t{0}; count: {1}", EntityType.LightWeightPolyline, dxf.LwPolylines.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Line, dxf.Lines.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Mesh, dxf.Meshes.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.MLine, dxf.MLines.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.MText, dxf.MTexts.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Point, dxf.Points.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.PolyfaceMesh, dxf.PolyfaceMeshes.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Polyline, dxf.Polylines.Count()); // Console.WriteLine("\t{0}; count: {1}", EntityType.Shape, dxf.Shapes.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Solid, dxf.Solids.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Spline, dxf.Splines.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Text, dxf.Texts.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Ray, dxf.Rays.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Underlay, dxf.Underlays.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Viewport, dxf.Viewports.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.Wipeout, dxf.Wipeouts.Count()); Console.WriteLine("\t{0}; count: {1}", EntityType.XLine, dxf.XLines.Count()); Console.WriteLine(); // the dxf version is controlled by the DrawingVariables property of the dxf document, // also a HeaderVariables instance or a DxfVersion can be passed to the constructor to initialize a new DxfDocument. // dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2018; // dxf.Save("sample 2018.dxf"); dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2013; dxf.Save("sample 2013.dxf"); dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2010; dxf.Save("sample 2010.dxf"); dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2007; dxf.Save("sample 2007.dxf"); dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2004; dxf.Save("sample 2004.dxf"); dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2000; dxf.Save("sample 2000.dxf"); // saving to binary dxf dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2013; dxf.Save("binary test.dxf", true); // DxfDocument test = DxfDocument.Load("binary test.dxf", new List<string> { @".\Support" }); DxfDocument test = DxfDocument.Load("binary test.dxf"); if (outputLog) { writer.Flush(); writer.Close(); } else { Console.WriteLine("Press a key to continue..."); Console.ReadLine(); } return(dxf); }
private static Transform GetClosestTransform(Vector3 pos, List <Transform> transforms, Dimension dimension) { Func <Vector3, Vector3, float> GetDistance = (a, b) => Vector2.Distance(a, b); if (dimension == Dimension.DDD) { GetDistance = (a, b) => Vector3.Distance(a, b); } if (transforms.Count == 0) { return(null); } else { float closest_transform_distance = 1000; Transform closest_transform = transforms[0]; foreach (Transform temp in transforms) { if (temp == null) { continue; } float distance = GetDistance(pos, temp.position); bool IsCloser = distance < closest_transform_distance; if (IsCloser) { closest_transform_distance = distance; closest_transform = temp; } } return(closest_transform); } }
public void Initialize(System.Collections.Hashtable properties) { if (properties.ContainsKey("ModelID")) { _modelID = (string)properties["ModelID"]; } if (properties.ContainsKey("TimeStepLength")) { _timeStepLength = Convert.ToDouble((string)properties["TimeStepLength"]); } // -- create a flow quanitity -- Dimension flowDimension = new Dimension(); flowDimension.SetPower(DimensionBase.Length, 3); flowDimension.SetPower(DimensionBase.Time, -1); Unit literPrSecUnit = new Unit("LiterPrSecond", 0.001, 0, "Liters pr Second"); Quantity flowQuantity = new Quantity(literPrSecUnit, "Flow", "Flow", global::OpenMI.Standard.ValueType.Scalar, flowDimension); // -- create leakage quantity -- Quantity leakageQuantity = new Quantity(literPrSecUnit, "Leakage", "Leakage", global::OpenMI.Standard.ValueType.Scalar, flowDimension); // -- create and populate elementset to represente the whole river network -- ElementSet fullRiverElementSet = new ElementSet("WholeRiver", "WholeRiver", ElementType.XYPolyLine, new SpatialReference("no reference")); for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); element.AddVertex(new Vertex(_xCoordinate[i], _yCoordinate[i], -999)); element.AddVertex(new Vertex(_xCoordinate[i + 1], _yCoordinate[i + 1], -999)); fullRiverElementSet.AddElement(element); } // --- populate input exchange items for flow to individual nodes --- for (int i = 0; i < _numberOfNodes; i++) { Element element = new Element(); element.ID = "Node:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes", "Node:" + i.ToString(), ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = elementSet; inputExchangeItem.Quantity = flowQuantity; _inputExchangeItems.Add(inputExchangeItem); } // --- Populate input exchange item for flow to the whole georeferenced river --- InputExchangeItem wholeRiverInputExchangeItem = new InputExchangeItem(); wholeRiverInputExchangeItem.ElementSet = fullRiverElementSet; wholeRiverInputExchangeItem.Quantity = flowQuantity; _inputExchangeItems.Add(wholeRiverInputExchangeItem); // --- Populate output exchange items for flow in river branches --- for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes", "Branch:" + i.ToString(), ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = flowQuantity; _outputExchangeItems.Add(outputExchangeItem); } // --- polulate output exchange items for leakage for individual branches -- for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes", "Branch:" + i.ToString(), ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = leakageQuantity; _outputExchangeItems.Add(outputExchangeItem); } // --- Populate output exchange item for leakage from the whole georeferenced river --- OutputExchangeItem wholeRiverOutputExchangeItem = new OutputExchangeItem(); wholeRiverOutputExchangeItem.ElementSet = fullRiverElementSet; wholeRiverOutputExchangeItem.Quantity = leakageQuantity; _outputExchangeItems.Add(wholeRiverOutputExchangeItem); // --- populate with initial state variables --- for (int i = 0; i < _numberOfNodes - 1; i++) { _flow[i] = 7; } _currentTimeStepNumber = 1; _initializeMethodWasInvoked = true; }
public override void Initialize() { Status = LinkableComponentStatus.Initializing; ReadArguments(); // Initialize storage vector _storage = new double[NumberOfElements]; for (int i = 0; i < NumberOfElements; i++) { _storage[i] = 0; } // -- Populate Exchange Items --- // Element set for a grid based (polygons) item Spatial2DRegularGrid regularGrid = new Spatial2DRegularGrid() { Description = "RegularGrid", Caption = "RegularGrid", Dx = _dx, Dy = _dy, X0 = _x0, Y0 = _y0, XCount = _xCount, YCount = _yCount, Orientation = _orientation, IsNodeBased = false, }; Spatial2DGridWrapper regularElmtSet = new Spatial2DGridWrapper(regularGrid); // Element set for a Polygon based item, of the lower left cell in the grid Element element0 = new Element("element:0"); element0.AddVertex(new Coordinate(_x0, _y0, 0)); element0.AddVertex(new Coordinate(_x0 + _dx, _y0, 0)); element0.AddVertex(new Coordinate(_x0 + _dx, _y0 + _dy, 0)); element0.AddVertex(new Coordinate(_x0, _y0 + _dy, 0)); // Element set for an ID based item, of the lower left cell in the grid ElementSet idSet = new ElementSet("FirstElement", "FirstElement", ElementType.IdBased); idSet.AddElement(element0); // is an IdBased set required to have elements? // Dimensions Dimension dimVolume = new Dimension(); dimVolume.SetPower(DimensionBase.Length, 3); Dimension dimLength = new Dimension(); dimLength.SetPower(DimensionBase.Length, 1); Dimension dimDischarge = new Dimension(); dimDischarge.SetPower(DimensionBase.Length, 3); dimDischarge.SetPower(DimensionBase.Time, -1); // Units Unit unitLiterStorage = new Unit("Storage", 0.001, 0.0, "Storage"); unitLiterStorage.Dimension = dimVolume; Unit unitGwLevel = new Unit("gw level", 1.0, 0.0, "Ground water level"); unitGwLevel.Dimension = dimLength; Unit unitDischarge = new Unit("Discharge", 0.001, 0, "Discharge into ground water model, [L/s]"); unitDischarge.Dimension = dimDischarge; // Quantities Quantity quantityStorage = new Quantity(unitLiterStorage, "Storage", "Storage"); Quantity quantityGwLevel = new Quantity(unitGwLevel, "Ground water level", "Ground water level"); Quantity quantityInflow = new Quantity(unitDischarge, "Inflow into ground water model", "Inflow"); // Storage input on the grid _storageInput = new EngineEInputItem("Grid.Storage", quantityStorage, regularElmtSet, this); _firstElementStorageInput = new EngineEInputItem("FirstElement.Storage", quantityStorage, idSet, this); // Storage output on the grid _storageOutput = new EngineEOutputItem("Grid.Storage", quantityStorage, regularElmtSet, this); _storageOutput.TimeSet.SetSingleTime(StartTime); _storageOutput.TimeSet.SetTimeHorizon(new Time(StartTime, EndTime)); // Storage output in the first element of the grid _firstElementStorageOutput = new EngineEOutputItem("FirstElement.Storage", quantityStorage, idSet, this); _firstElementStorageOutput.TimeSet.SetSingleTime(StartTime); _firstElementStorageOutput.TimeSet.SetTimeHorizon(new Time(StartTime, EndTime)); // Ground water level output. Calculated as (_gwBaseLevel + 0.1*storage height), assuming that the // water can populate 10% of the ground volume. EngineDOutputItem gwLevelOutput = new EngineDOutputItem("Grid.gwLevel", quantityGwLevel, regularElmtSet, this); gwLevelOutput.StoreValuesInExchangeItem = false; gwLevelOutput.ValueGetter = delegate() { IList <double> res = new List <double>(NumberOfElements); for (int i = 0; i < NumberOfElements; i++) { // Convert storage from liters to m3 and find the height. double storageHeight = 0.001 * _storage[i] / (_dx * _dy); res.Add(_gwBaseLevel + 10 * storageHeight); } return(new ValueSet(new List <IList> { (IList)res })); }; // Ground water inflow in the grid EngineDInputItem gwInflow = new EngineDInputItem("Grid.Inflow", quantityInflow, regularElmtSet, this); gwInflow.ValueSetter = delegate(ITimeSpaceValueSet values) { IList elmtValues = values.GetElementValuesForTime(0); for (int i = 0; i < NumberOfElements; i++) { // Values arrive in [L/s], storage is in liters. _storage[i] += (double)elmtValues[i] * _timeStepLengthInSeconds; if (_storage[i] < 0) // inflow can be negative, but storage can not be zero. Mass error here :-( { _storage[i] = 0; } } }; EngineOutputItems.Add(_storageOutput); EngineOutputItems.Add(_firstElementStorageOutput); EngineOutputItems.Add(gwLevelOutput); EngineInputItems.Add(_storageInput); EngineInputItems.Add(_firstElementStorageInput); if (_useMultiInput) { EngineInputItems.Add(new EngineMultiInputItemWrapper(gwInflow, this)); } else { EngineInputItems.Add(gwInflow); } Status = LinkableComponentStatus.Initialized; }
public static BuilderTextShadow GetTextShadow(this StyleSheet styleSheet, StyleProperty styleProperty) { Dimension offsetX = new Dimension(0f, Dimension.Unit.Pixel); Dimension offsetY = new Dimension(0f, Dimension.Unit.Pixel); Dimension blurRadius = new Dimension(0f, Dimension.Unit.Pixel); var color = Color.clear; var valueCount = styleProperty.values.Length; if (valueCount >= 2) { int i = 0; var valueType = styleProperty.values[i].valueType; bool wasColorFound = false; if (valueType == StyleValueType.Color || valueType == StyleValueType.Enum) { color = styleSheet.GetColor(styleProperty.values[i++]); wasColorFound = true; } if (i + 1 < valueCount) { valueType = styleProperty.values[i].valueType; var valueType2 = styleProperty.values[i + 1].valueType; if (valueType == StyleValueType.Dimension && valueType2 == StyleValueType.Dimension) { var valueX = styleProperty.values[i++]; var valueY = styleProperty.values[i++]; offsetX = styleSheet.GetDimension(valueX); offsetY = styleSheet.GetDimension(valueY); } } if (i < valueCount) { valueType = styleProperty.values[i].valueType; if (valueType == StyleValueType.Dimension) { var valueBlur = styleProperty.values[i++]; blurRadius = styleSheet.GetDimension(valueBlur); } else if (valueType == StyleValueType.Color || valueType == StyleValueType.Enum) { if (!wasColorFound) { color = styleSheet.GetColor(styleProperty.values[i]); } } } if (i < valueCount) { valueType = styleProperty.values[i].valueType; if (valueType == StyleValueType.Color || valueType == StyleValueType.Enum) { if (!wasColorFound) { color = styleSheet.GetColor(styleProperty.values[i]); } } } } return(new BuilderTextShadow { offsetX = offsetX, offsetY = offsetY, blurRadius = blurRadius, color = color }); }
public Task <bool> Create(Dimension entity) { throw new NotImplementedException(); }
public async Task <bool> Delete(Dimension entity) { _db.Dimensions.Remove(entity); return(await Save()); }
public async Task <bool> Update(Dimension entity) { _db.Dimensions.Update(entity); return(await Save()); }
/// <summary> /// Get all data related to user (profiles + dimensions) /// </summary> /// <param name="idProduct"></param> /// <param name="idClient"></param> /// <returns></returns> public ActionResponse GetDataUserAction(int idProduct, int idClient) { try { // Check for product var oProduct = productsRepository.GetProduct(idProduct); if (oProduct == null) { return(utilities.Response((int)CodeStatusEnum.NO_CONTENT, "No existe el producto", null)); } // Get user (will check against idUserExternal) var oUser = this.usersRepository.GetUserv2(idClient.ToString(), idProduct); if (oUser == null) { return(utilities.Response((int)CodeStatusEnum.NO_CONTENT, "El usuario no existe o no está relacionado con el producto", null)); } if (!oUser.Active.Value) { return(utilities.Response((int)CodeStatusEnum.CONFLICT, "El usuario indicado no se encuentra activo en la plataforma", null)); } int idUser = oUser.IdUser; // ID USER FREEMIUM // Get subscription data var subscription = subscriptionsRepository.GetUserCurrentSubscription(idUser); if (subscription == null) { return(utilities.Response((int)CodeStatusEnum.NO_CONTENT, "No se ha podido determinar la suscripción del usuario", null)); } // Profile about subscription var profile = profilesRepository.GetProfile(subscription.IdProfile.Value); if (profile == null) { return(utilities.Response((int)CodeStatusEnum.NO_CONTENT, "No se ha podido identificar el perfil asociado al usuario", null)); } int idProfile = profile.IdProfile; // Get dimensions by profile var dimensions = dimensionsRepository.GetProfileDimensions(idProfile); // Travel dimensions, if type is consumible, will get user dimensions vinculated List <Dimension> newDimensions = new List <Dimension>(); if (dimensions.Count > 0) { foreach (var item in dimensions) // item = dimension object (from repository) { Dimension dimensionOut = new Dimension() { idDimension = (int)item.IdDimension, idDimensionType = item.IdDimensionType.Value, idDimensionCategory = item.DimensionsCategories.IdDimensionCategory, nameDimension = item.Description, tagDimension = item.TagName, tagDimensionCategory = item.DimensionsCategories.TagName }; // ProfileDimension associated var profileDimension = profilesDimensionsRepository.GetProfileDimensionPD(idProfile, dimensionOut.idDimension); if (profileDimension == null) { return(utilities.Response((int)CodeStatusEnum.NO_CONTENT, "No se se pudo obtener la relación del perfil con la dimensión", null)); } switch ((int)item.IdDimensionType) { case (int)DimensionTypeEnum.NUMERIC: case (int)DimensionTypeEnum.SWITCH: if ((int)item.IdDimensionType == (int)DimensionTypeEnum.NUMERIC) { if (profileDimension.Value == null) { return(utilities.Response((int)CodeStatusEnum.CONFLICT, "No se ha detectado ningún valor para el atributo 'Value' en Dimensión " + dimensionOut.idDimension + ", por favor corregir", null)); } dimensionOut.currentValue = profileDimension.Value.Value; } else { if (profileDimension.SwitchValue == null) { return(utilities.Response((int)CodeStatusEnum.CONFLICT, "No se ha detectado ningún valor para el atributo 'SwitchValue' en Dimensión " + dimensionOut.idDimension + ", por favor corregir", null)); } dimensionOut.currentValue = profileDimension.SwitchValue.Value; } break; case (int)DimensionTypeEnum.CONSUMIBLE: // Get UserDimension var userDimension = usersDimensionsRepository.GetUserDimension(item.IdDimension, subscription.IdSubscription); bool valSetWithNewUD = false; if (userDimension == null) { // If user dimension is not set, we will create it in order to normalize user configuration var newDimension = usersDimensionsRepository.NewUserDimension(item.IdDimension, subscription.IdSubscription); if (newDimension.CurrentValue == null) { return(utilities.Response((int)CodeStatusEnum.CONFLICT, "Imposible determinar 'CurrentValue' para Dimensión " + item.IdDimension + " y Suscripción " + subscription.IdSubscription + ", por favor corregir", null)); } dimensionOut.currentValue = newDimension.CurrentValue.Value; valSetWithNewUD = true; //return utilities.Response((int)CodeStatusEnum.NO_CONTENT, "No se se pudo obtener la relación de la dimensión con el usuario", null); } if (!valSetWithNewUD) { if (userDimension.CurrentValue == null) { return(utilities.Response((int)CodeStatusEnum.CONFLICT, "Imposible determinar 'CurrentValue' para Dimensión " + item.IdDimension + " y Suscripción " + subscription.IdSubscription + ", por favor corregir", null)); } dimensionOut.currentValue = userDimension.CurrentValue.Value; } if (profileDimension.Value == null) { return(utilities.Response((int)CodeStatusEnum.CONFLICT, "No se ha detectado ningún valor para el atributo 'Value' en Dimensión " + dimensionOut.idDimension + ", por favor corregir", null)); } dimensionOut.originalValue = profileDimension.Value.Value; break; } DimensionTypeEnum dimensionTypeEnum = (DimensionTypeEnum)dimensionOut.idDimensionType; dimensionOut.nameDimensionType = dimensionTypeEnum.ToString(); // Add object newDimensions.Add(dimensionOut); } } // Response object GetDataUserResponse response = new GetDataUserResponse { idSubscription = subscription.IdSubscription, dateCreated = subscription.DateCreated.Value, profile = new Profile { idProfile = profile.IdProfile, name = profile.Name, description = profile.Description, tagName = profile.TagName, active = profile.Active, paid = profile.Paid }, dimensions = newDimensions }; return(utilities.Response((int)CodeStatusEnum.OK, "OK", response)); } catch (Exception e) { return(utilities.Response((int)CodeStatusEnum.INTERNAL_ERROR, "Error desconocido en el sistema: " + e.Message, null)); } }
public void Test_SimpleRNN_Execute_Linear() { // Initialize data. Data2D data = new Data2D(1, 3, 3, 4); int l = 0; for (int b = 0; b < 4; ++b) { for (int w = 0; w < 3; ++w) { for (int c = 0; c < 3; ++c) { l += 1; data[0, w, c, b] = l % 5 + 1; } } } // Initialize parameters. Data2D pms = new Data2D(1, 4, 4, 3); int k = 0; for (int i = 0; i < 3; ++i) { for (int u = 0; u < 4; ++u) { k += 1; pms[0, i, u, 0] = k % 5 - 2; } } k = 0; for (int i = 0; i < 4; ++i) { for (int u = 0; u < 4; ++u) { k += 1; pms[0, i, u, 1] = k % 5 - 2; } } pms[0, 0, 0, 2] = 1.0; pms[0, 0, 1, 2] = -1.0; pms[0, 0, 2, 2] = 2.0; pms[0, 0, 3, 2] = -4.0; SimpleRNNLayer rnn = new SimpleRNNLayer(4, 3, p => { }); rnn.SetWeights(pms); rnn.SetInput(data); rnn.Execute(); Data2D output = rnn.GetOutput() as Data2D; // Checking sizes Dimension dim = output.GetDimension(); Assert.AreEqual(dim.b, 4); Assert.AreEqual(dim.c, 4); Assert.AreEqual(dim.h, 1); Assert.AreEqual(dim.w, 1); // Checking calculation Assert.AreEqual(output[0, 0, 0, 0], -54, 0.000001); Assert.AreEqual(output[0, 0, 1, 0], -39, 0.000001); Assert.AreEqual(output[0, 0, 2, 0], 36, 0.000001); Assert.AreEqual(output[0, 0, 3, 0], 72, 0.000001); Assert.AreEqual(output[0, 0, 0, 1], 12, 0.000001); Assert.AreEqual(output[0, 0, 1, 1], -19, 0.000001); Assert.AreEqual(output[0, 0, 2, 1], -10, 0.000001); Assert.AreEqual(output[0, 0, 3, 1], 10, 0.000001); Assert.AreEqual(output[0, 0, 0, 2], -72, 0.000001); Assert.AreEqual(output[0, 0, 1, 2], 16, 0.000001); Assert.AreEqual(output[0, 0, 2, 2], 74, 0.000001); Assert.AreEqual(output[0, 0, 3, 2], 68, 0.000001); Assert.AreEqual(output[0, 0, 0, 3], -161, 0.000001); Assert.AreEqual(output[0, 0, 1, 3], -14, 0.000001); Assert.AreEqual(output[0, 0, 2, 3], 158, 0.000001); Assert.AreEqual(output[0, 0, 3, 3], 141, 0.000001); }
private void B_Convert_Click(object sender, EventArgs e) { //Check number of selected files int fNum = _M4Files.Length; if (fNum == 0) { return; } SaveFileDialog aDlg = new SaveFileDialog(); aDlg.Filter = "NetCDF File (*.nc)|*.nc"; if (aDlg.ShowDialog() == DialogResult.OK) { string outFile = aDlg.FileName; //Show progressbar toolStripProgressBar1.Visible = true; toolStripProgressBar1.Value = 0; this.Cursor = Cursors.WaitCursor; //File loop int i; //NetCDFData CNetCDFData = new NetCDFData(); NetCDFDataInfo outDataInfo = new NetCDFDataInfo(); List <string> varList = new List <string>(); MICAPS4DataInfo inDataInfo = new MICAPS4DataInfo(); inDataInfo.ReadDataInfo(_M4Files[0]); //Set data info outDataInfo.FileName = outFile; outDataInfo.IsGlobal = false; outDataInfo.isLatLon = true; outDataInfo.MissingValue = inDataInfo.MissingValue; outDataInfo.unlimdimid = 2; //Add dimensions: lon, lat, time Dimension lonDim = outDataInfo.AddDimension("lon", inDataInfo.XNum); Dimension latDim = outDataInfo.AddDimension("lat", inDataInfo.YNum); Dimension timeDim = outDataInfo.AddDimension("time", -1); //Add variables outDataInfo.AddVariable("lon", NetCDF4.NcType.NC_DOUBLE, new Dimension[] { lonDim }); outDataInfo.AddVariableAttribute("lon", "units", "degrees_east"); outDataInfo.AddVariableAttribute("lon", "long_name", "longitude"); outDataInfo.AddVariable("lat", NetCDF4.NcType.NC_DOUBLE, new Dimension[] { latDim }); outDataInfo.AddVariableAttribute("lat", "units", "degrees_north"); outDataInfo.AddVariableAttribute("lat", "long_name", "latitude"); outDataInfo.AddVariable("time", NetCDF4.NcType.NC_DOUBLE, new Dimension[] { timeDim }); outDataInfo.AddVariableAttribute("time", "units", "days since 1-1-1 00:00:00"); outDataInfo.AddVariableAttribute("time", "long_name", "time"); //outDataInfo.AddVariableAttribute("time", "delta_t", "0000-00-01 00:00:00"); outDataInfo.AddVariable("dust", NetCDF4.NcType.NC_DOUBLE, new Dimension[] { timeDim, latDim, lonDim }); outDataInfo.AddVariableAttribute("dust", "units", "ug/m-3"); outDataInfo.AddVariableAttribute("dust", "long_name", "dust concentration"); outDataInfo.AddVariableAttribute("dust", "missing_value", 9999); //Add global attributes outDataInfo.AddGlobalAttribute("title", "Asian dust storm forecast"); outDataInfo.AddGlobalAttribute("model", "CUACE/Dust"); outDataInfo.AddGlobalAttribute("institute", "Chinese Academy of Meteological Sciences"); //Creat NetCDF file outDataInfo.CreateNCFile(outFile); DateTime sTime = DateTime.Parse("0001-1-1 00:00:00"); for (i = 0; i < fNum; i++) { string aFile = _M4Files[i]; if (i > 0) { inDataInfo = new MICAPS4DataInfo(); inDataInfo.ReadDataInfo(aFile); } else { //Write lon,lat data outDataInfo.WriteVar("lon", inDataInfo.X); outDataInfo.WriteVar("lat", inDataInfo.Y); } //Write time data object[] tData = new object[1]; tData[0] = inDataInfo.DateTime.Subtract(sTime).TotalDays; int[] start = new int[1]; int[] count = new int[1]; start[0] = i; count[0] = 1; outDataInfo.WriteVara("time", start, count, tData); //Write dust data object[] dustData = new object[inDataInfo.XNum * inDataInfo.YNum]; for (int m = 0; m < inDataInfo.YNum; m++) { for (int n = 0; n < inDataInfo.XNum; n++) { dustData[m * inDataInfo.XNum + n] = inDataInfo.GridData[m, n]; } } start = new int[3]; start[0] = i; start[1] = 0; start[2] = 0; count = new int[3]; count[0] = 1; count[1] = latDim.DimLength; count[2] = lonDim.DimLength; outDataInfo.WriteVara("dust", start, count, dustData); //Set progressbar value toolStripProgressBar1.Value = (int)((double)(i + 1) / (double)fNum * 100); Application.DoEvents(); } outDataInfo.CloseNCFile(); //Hide progressbar toolStripProgressBar1.Visible = false; toolStripProgressBar1.Value = 0; this.Cursor = Cursors.Default; } }
protected DimensionConstraint(View view, Dimension dimension, float constant = 0f) { View = view; Dimension = dimension; Constant = constant; }
/// <summary> /// The List Metric Definitions operation lists the metric definitions /// for the resource. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the target resource to get /// metrics for. /// </param> /// <param name='filterString'> /// Optional. An OData $filter expression that supports querying by the /// name of the metric definition. For example, "name.value eq /// 'Percentage CPU'". Name is optional, meaning the expression may be /// "". /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Metric Definitions operation response. /// </returns> public async Task <MetricDefinitionListResponse> GetMetricDefinitionsAsync(string resourceUri, string filterString, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("filterString", filterString); TracingAdapter.Enter(invocationId, this, "GetMetricDefinitionsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + Uri.EscapeDataString(resourceUri); url = url + "/metricDefinitions"; List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=2014-04-01"); List <string> odataFilter = new List <string>(); if (filterString != null) { odataFilter.Add(Uri.EscapeDataString(filterString)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result MetricDefinitionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MetricDefinitionListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { MetricDefinitionCollection metricDefinitionCollectionInstance = new MetricDefinitionCollection(); result.MetricDefinitionCollection = metricDefinitionCollectionInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { MetricDefinition metricDefinitionInstance = new MetricDefinition(); metricDefinitionCollectionInstance.Value.Add(metricDefinitionInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { LocalizableString nameInstance = new LocalizableString(); metricDefinitionInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true)); metricDefinitionInstance.Unit = unitInstance; } JToken primaryAggregationTypeValue = valueValue["primaryAggregationType"]; if (primaryAggregationTypeValue != null && primaryAggregationTypeValue.Type != JTokenType.Null) { AggregationType primaryAggregationTypeInstance = ((AggregationType)Enum.Parse(typeof(AggregationType), ((string)primaryAggregationTypeValue), true)); metricDefinitionInstance.PrimaryAggregationType = primaryAggregationTypeInstance; } JToken resourceUriValue = valueValue["resourceUri"]; if (resourceUriValue != null && resourceUriValue.Type != JTokenType.Null) { string resourceUriInstance = ((string)resourceUriValue); metricDefinitionInstance.ResourceUri = resourceUriInstance; } JToken metricAvailabilitiesArray = valueValue["metricAvailabilities"]; if (metricAvailabilitiesArray != null && metricAvailabilitiesArray.Type != JTokenType.Null) { foreach (JToken metricAvailabilitiesValue in ((JArray)metricAvailabilitiesArray)) { MetricAvailability metricAvailabilityInstance = new MetricAvailability(); metricDefinitionInstance.MetricAvailabilities.Add(metricAvailabilityInstance); JToken timeGrainValue = metricAvailabilitiesValue["timeGrain"]; if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null) { TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue)); metricAvailabilityInstance.TimeGrain = timeGrainInstance; } JToken retentionValue = metricAvailabilitiesValue["retention"]; if (retentionValue != null && retentionValue.Type != JTokenType.Null) { TimeSpan retentionInstance = XmlConvert.ToTimeSpan(((string)retentionValue)); metricAvailabilityInstance.Retention = retentionInstance; } JToken locationValue = metricAvailabilitiesValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { MetricLocation locationInstance = new MetricLocation(); metricAvailabilityInstance.Location = locationInstance; JToken tableEndpointValue = locationValue["tableEndpoint"]; if (tableEndpointValue != null && tableEndpointValue.Type != JTokenType.Null) { string tableEndpointInstance = ((string)tableEndpointValue); locationInstance.TableEndpoint = tableEndpointInstance; } JToken tableInfoArray = locationValue["tableInfo"]; if (tableInfoArray != null && tableInfoArray.Type != JTokenType.Null) { foreach (JToken tableInfoValue in ((JArray)tableInfoArray)) { MetricTableInfo metricTableInfoInstance = new MetricTableInfo(); locationInstance.TableInfo.Add(metricTableInfoInstance); JToken tableNameValue = tableInfoValue["tableName"]; if (tableNameValue != null && tableNameValue.Type != JTokenType.Null) { string tableNameInstance = ((string)tableNameValue); metricTableInfoInstance.TableName = tableNameInstance; } JToken startTimeValue = tableInfoValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); metricTableInfoInstance.StartTime = startTimeInstance; } JToken endTimeValue = tableInfoValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTime endTimeInstance = ((DateTime)endTimeValue); metricTableInfoInstance.EndTime = endTimeInstance; } JToken sasTokenValue = tableInfoValue["sasToken"]; if (sasTokenValue != null && sasTokenValue.Type != JTokenType.Null) { string sasTokenInstance = ((string)sasTokenValue); metricTableInfoInstance.SasToken = sasTokenInstance; } JToken sasTokenExpirationTimeValue = tableInfoValue["sasTokenExpirationTime"]; if (sasTokenExpirationTimeValue != null && sasTokenExpirationTimeValue.Type != JTokenType.Null) { DateTime sasTokenExpirationTimeInstance = ((DateTime)sasTokenExpirationTimeValue); metricTableInfoInstance.SasTokenExpirationTime = sasTokenExpirationTimeInstance; } } } JToken partitionKeyValue = locationValue["partitionKey"]; if (partitionKeyValue != null && partitionKeyValue.Type != JTokenType.Null) { string partitionKeyInstance = ((string)partitionKeyValue); locationInstance.PartitionKey = partitionKeyInstance; } } } } JToken propertiesSequenceElement = ((JToken)valueValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); metricDefinitionInstance.Properties.Add(propertiesKey, propertiesValue); } } JToken dimensionsArray = valueValue["dimensions"]; if (dimensionsArray != null && dimensionsArray.Type != JTokenType.Null) { foreach (JToken dimensionsValue in ((JArray)dimensionsArray)) { Dimension dimensionInstance = new Dimension(); metricDefinitionInstance.Dimensions.Add(dimensionInstance); JToken nameValue2 = dimensionsValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { LocalizableString nameInstance2 = new LocalizableString(); dimensionInstance.Name = nameInstance2; JToken valueValue3 = nameValue2["value"]; if (valueValue3 != null && valueValue3.Type != JTokenType.Null) { string valueInstance2 = ((string)valueValue3); nameInstance2.Value = valueInstance2; } JToken localizedValueValue2 = nameValue2["localizedValue"]; if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null) { string localizedValueInstance2 = ((string)localizedValueValue2); nameInstance2.LocalizedValue = localizedValueInstance2; } } JToken valuesArray = dimensionsValue["values"]; if (valuesArray != null && valuesArray.Type != JTokenType.Null) { foreach (JToken valuesValue in ((JArray)valuesArray)) { LocalizableString localizableStringInstance = new LocalizableString(); dimensionInstance.Values.Add(localizableStringInstance); JToken valueValue4 = valuesValue["value"]; if (valueValue4 != null && valueValue4.Type != JTokenType.Null) { string valueInstance3 = ((string)valueValue4); localizableStringInstance.Value = valueInstance3; } JToken localizedValueValue3 = valuesValue["localizedValue"]; if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null) { string localizedValueInstance3 = ((string)localizedValueValue3); localizableStringInstance.LocalizedValue = localizedValueInstance3; } } } } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public void AddValue(Dimension value) { RegisterValue(m_Dimensions, StyleValueType.Dimension, value); }
protected ObjetJeu(Coordonnée p_coordonnée, Dimension p_dimension, int p_valeur) : base(p_coordonnée, p_dimension) { Valeur = p_valeur; }
[Obsolete("Use constructor which takes creation function instead.")] // Can be removed 20220803. public StatisticItem([NotNull] string name, [NotNull] Drawable content, [CanBeNull] Dimension dimension = null) : this(name, () => content, true, dimension) { }