示例#1
0
 /// <summary>
 /// Instantiates a new instance of <see cref="ImagePart"/>.
 /// </summary>
 /// <param name="imageUrl">The url to the image.</param>
 /// <param name="text">The text.</param>
 /// <param name="linkUrl">The url to the link.</param>
 /// <param name="dimensions">The dimensions of the image.</param>
 public ImagePart(string imageUrl, string text, string linkUrl, Dimensions dimensions)
 {
     ImageUrl = imageUrl;
     Text = text;
     LinkUrl = linkUrl;
     Dimensions = dimensions;
 }
        /// <summary>
        /// Create a <see cref="Storyboard"/> to be used to animate the view, 
        /// based on the animation configuration supplied at initialization
        /// time and the new view position and size.
        /// </summary>
        /// <param name="view">The view to create the animation for.</param>
        /// <param name="dimensions">The view dimensions.</param>
        protected override IObservable<Unit> CreateAnimationCore(FrameworkElement view, Dimensions dimensions)
        {
            var fromValue = IsReverse ? 1.0 : 0.0;
            var toValue = IsReverse ? 0.0 : 1.0;

            var animatedProperty = AnimatedProperty;
            if (animatedProperty.HasValue)
            {
                var storyboard = new Storyboard();
                var @finally = default(Action);
                switch (animatedProperty.Value)
                {
                    case AnimatedPropertyType.Opacity:
                        view.Opacity = fromValue;
                        storyboard.Children.Add(CreateOpacityAnimation(view, fromValue, toValue));
                        @finally = () => view.Opacity = toValue;
                        break;
                    case AnimatedPropertyType.ScaleXY:
                        // TODO: implement this layout animation option
                        throw new NotImplementedException();
                    default:
                        throw new InvalidOperationException(
                            "Missing animation for property: " + animatedProperty.Value);
                }

                return new StoryboardObservable(storyboard, @finally);
            }

            throw new InvalidOperationException(
                "Missing animated property from the animation configuration.");
        }
示例#3
0
        Image GetImageFromGoogleCharts(Dimensions dimensions)
        {
            var chl = "&chl=" + Uri.EscapeDataString(GetValue<string>("text"));
              var chs = string.Format("&chs={0}x{1}", dimensions.Width,
                  dimensions.Height);
              var choe = "&choe=" + GetEncodingString();
              var chld = string.Format("&chld={0}|{1}", GetValue<string>("error_correction"),
                   GetValue<int>("margin"));
              var url = "http://chart.apis.google.com/chart?cht=qr"
            + chl + chs + choe + chld;

              var procedure = new Procedure("file-uri-load");

              try
            {
              var returnArgs = procedure.Run(url, url);

              return returnArgs[0] as Image;
            }
              catch (GimpSharpException e)
            {
              new Message(e.Message);
              return null;
            }
        }
 //---------------------------------------------------------------------
 public OutputRaster(string     path,
     Dimensions dimensions)
     : base(path, dimensions)
 {
     this.pixelsWritten = 0;
     this.disposed = false;
 }
示例#5
0
	/**
	 * Constructs and loads the map
	 * @param players The number of players in the game
	 */
	public void construct (int players) {
		// Get a map from the collections
		Maps mapsCollection = Maps.S;
		GameObject mapPrefab = mapsCollection.getRandomMap (players);
		GameController.showDebug ("map: " + mapPrefab.name);

		// Instantiate the new map
		GameObject map = Instantiate (mapPrefab, new Vector3 (0, -0.1f, 0), Quaternion.identity) as GameObject;

		// For some reason, the map is instatiated upside-down
		map.transform.Rotate (0, 180, 0);

		// Name the map a cool name
		map.name = "Map";

		// Set the parent
		map.transform.SetParent (GameObject.Find ("Maps").transform);

		// Get the variables from the map
		mapScript = map.GetComponent<Map> ();

		// Get the dimensions
		dimensions = mapScript.dimensions;

		// Resize the map
		map.transform.localScale = new Vector3 ((dimensions.width * 0.10f), 1, (dimensions.height * 0.10f));

		// Move the map into place
		map.transform.position = new Vector3 (((mapScript.dimensions.width / 2) - offset), map.transform.position.y, ((mapScript.dimensions.height / 2) - offset));

		// Setup the resources
		resourceTileController.initResources (mapScript.resourceTile);
	}
示例#6
0
 public Bathroom(Dimensions dimensions, bool hasToilet, bool hasShower, bool hasBath, bool hasSink)
 {
     Dimensions = dimensions;
     HasToilet = hasToilet;
     HasShower = hasShower;
     HasBath = hasBath;
     HasSink = hasSink;
 }
 //---------------------------------------------------------------------
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 public Raster(string     path,
     Dimensions dimensions)
 {
     this.path = path;
     this.dimensions = dimensions;
     this.disposed = false;
     UpdatePixelCount();
 }
示例#8
0
 public static string Path(Dimensions dim, int x, int z)
 {
     string path = "world/";
     if (dim != Dimensions.Overworld)
         path += "DIM" + ((int)dim) + "/";
     path += "region/r." + (x >> 9) + "." + (z >> 9) + ".mca";
     return path;
 }
示例#9
0
		//---------------------------------------------------------------------

		public Raster(string     path,
		              Dimensions dimensions,
		              IMetadata  metadata)
		{
			this.path = path;
			this.dimensions = dimensions;
			this.metadata = metadata;
			this.disposed = false;
		}
		//---------------------------------------------------------------------

		public OutputRaster(string     path,
		                    Dimensions dimensions,
		                    IMetadata  metadata)
			: base(path, dimensions, metadata)
		{
			this.pixelsWritten = 0;
			this.pixelCount = dimensions.Rows * dimensions.Columns;
			this.disposed = false;
		}
        /// <summary>
        /// Create an observable animation to be used to animate the view, 
        /// based on the animation configuration supplied at initialization
        /// time and the new view position and size.
        /// </summary>
        /// <param name="view">The view to create the animation for.</param>
        /// <param name="dimensions">The view dimensions</param>
        /// <returns>
        /// An observable sequence that starts an animation when subscribed to,
        /// stops the animation when disposed, and that completes 
        /// simultaneously with the underlying animation.
        /// </returns>
        protected override IObservable<Unit> CreateAnimationCore(FrameworkElement view, Dimensions dimensions)
        {
            Canvas.SetLeft(view, dimensions.X);
            Canvas.SetTop(view, dimensions.Y);
            view.Width = dimensions.Width;
            view.Height = dimensions.Height;

            return base.CreateAnimationCore(view, dimensions);
        }
#pragma warning restore 0067

        public PlatformInfoProvider()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => {
                double scale = (double)Application.Current.Host.Content.ScaleFactor / 100;
                int h = (int)Math.Ceiling(Application.Current.Host.Content.ActualHeight * scale);
                int w = (int)Math.Ceiling(Application.Current.Host.Content.ActualWidth * scale);               
                _screenResolution = new Dimensions(h, w);
            });
        }
示例#13
0
        public static McaFile Load(Dimensions dim, int x, int z)
        {
            string path = McaFile.Path(dim, x, z);
            if (File.Exists(path) == false)
                return null;

            McaFile mca = new McaFile(dim, x, z);
            mca.LoadFromFile(path);
            return mca;
        }
示例#14
0
 public Matrix2D GetSubMatrix(int index, Dimensions dimsType)
 {
     switch (dimsType)
     {
         case Dimensions.TimeDimension:
             throw new InvalidOperationException("Can't get submatrix for this dimension");
         case Dimensions.Thickness:
             if (index < thickness)
             {
                 Matrix2D result = new Matrix2D(width, height);
                 for (int i = 0; i < width; i++)
                 {
                     for (int j = 0; j < height; j++)
                     {
                         result[i, j] = this[i, j, index];
                     }
                 }
                 return result;
             }
             else
                 throw new ArgumentException("Invalid indexer");
         case Dimensions.Height:
             if (index < height)
             {
                 Matrix2D result = new Matrix2D(width, thickness);
                 for (int i = 0; i < width; i++)
                 {
                     for (int j = 0; j < thickness; j++)
                     {
                         result[i, j] = this[i, index, j];
                     }
                 }
                 return result;
             }
             else
                 throw new ArgumentException("Invalid indexer");
         case Dimensions.Width:
             if (index < width)
             {
                 Matrix2D result = new Matrix2D(height, thickness);
                 for (int i = 0; i < height; i++)
                 {
                     for (int j = 0; j < thickness; j++)
                     {
                         result[i, j] = this[index, i, j];
                     }
                 }
                 return result;
             }
             else
                 throw new ArgumentException("Invalid indexer");
         default:
             throw new Exception("Something strange has happened");
     }
 }
		public static Dimensions ResizeWidthMaintainAspectRatio(Dimensions originalDimensions, int maximumWidth)
		{
			int resizedWidth = originalDimensions.Width > maximumWidth 
								? maximumWidth
								: originalDimensions.Width;

			float resizedHeight = ((float)resizedWidth) / ((float)originalDimensions.Width);
			resizedHeight = resizedHeight * originalDimensions.Height;

			return new Dimensions(resizedWidth, (int)resizedHeight);
		}
		public static Dimensions ResizeHeightMaintainAspectRatio(Dimensions originalDimensions, int maximumHeight)
		{
			var resizedHeight = originalDimensions.Height > maximumHeight
								? maximumHeight
								: originalDimensions.Height;

			var resizedWidth = ((float)resizedHeight) / ((float)originalDimensions.Height);
			resizedWidth = resizedWidth * originalDimensions.Width;

			return new Dimensions((int)resizedWidth, resizedHeight);
		}
示例#17
0
    /// <summary>
    /// Returns the dimensions of a figure rotated by certain angle.
    /// </summary>
    /// <param name="dimensions">The dimensions of the figure to be rotated.</param>
    /// <param name="angle">The angle of rotation.</param>
    /// <returns></returns>
    public static Dimensions GetDimensionsAfterRotation(Dimensions dimensions, double angle)
    {
        double sine = Math.Abs(Math.Sin(angle));
        double cosine = Math.Abs(Math.Cos(angle));

        double newWidth = (sine * dimensions.height) + (cosine * dimensions.width);
        double newHeight = (sine * dimensions.width) + (cosine * dimensions.height);

        var newSize = new Dimensions(newWidth, newHeight);
        return newSize;
    }
示例#18
0
 private void SetZero(int i, int j, int startIndex, int endIndex, Dimensions dimension, LayerData layer)
 {
     int length = endIndex - startIndex;
     double[] zeroArray = new double[length];
     for (int k = 0; k < length; k++)
     {
         zeroArray[k] = 0;
     }
     layer.U.SetColumn(i, j, startIndex, dimension, zeroArray);
     layer.V.SetColumn(i, j, startIndex, dimension, zeroArray);
     layer.W.SetColumn(i, j, startIndex, dimension, zeroArray);
     layer.T.SetColumn(i, j, startIndex, dimension, zeroArray);
 }
示例#19
0
        public PreviewRenderer(Preview preview, Gdk.GC gc, Dimensions dimensions)
        {
            _window = preview.GdkWindow;
              _gc = gc;
              _width = dimensions.Width - 1;
              _height = dimensions.Height - 1;

              var colormap = Colormap.System;
              _inactive = new Gdk.Color(0xff, 0, 0);
              _active = new Gdk.Color(0, 0xff, 0);
              colormap.AllocColor(ref _inactive, true, true);
              colormap.AllocColor(ref _active, true, true);
        }
        /// <summary>
        /// Tries to get the display unit for the specified dimension.
        /// </summary>
        /// <param name="d">The dimension.</param>
        /// <param name="symbol">The symbol.</param>
        /// <param name="q">The unit.</param>
        /// <returns><c>true</c> if the unit was found, <c>false</c> otherwise.</returns>
        public bool TryGetDisplayUnit(Dimensions d, out string symbol, out DynamicQuantity q)
        {
            if (this.displayUnits.TryGetValue(d, out symbol))
            {
                if (this.units.TryGetValue(symbol, out q))
                {
                    return true;
                }
            }

            symbol = null;
            q = default(DynamicQuantity);
            return false;
        }
示例#21
0
        public McaFile(Dimensions dim, int x, int z)
        {
            this.dimension = dim;
            this.x = x;
            this.z = z;

            //Decode chunk data
            /*MemoryStream ms = new MemoryStream(buffer, offset, sectors * 4096, false);
            using (GZipStream gzip = new GZipStream (ms, CompressionMode.Decompress))
            {
                EndianBinaryReader r = new EndianBinaryReader(EndianBitConverter.Big, gzip);
                Tag.ReadTag(r);
            }*/
        }
示例#22
0
        public bool Init(string expr, Dimensions dimensions)
        {
            var cp = CodeDomProvider.CreateProvider("c#");

              var cpar = new CompilerParameters() {
            GenerateInMemory = true, GenerateExecutable = false};
              cpar.ReferencedAssemblies.Add("System.dll");
              cpar.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
              string src =
            "using System;"+
            "class myclass : Gimp.Splitter.MyClassBase" +
            "{"+
            "public myclass(){}"+
            "public override double eval(double x,double y)"+
            "{"+
            "return "+ expr +";"+
            "}"+
            "}";
              var cr = cp.CompileAssemblyFromSource(cpar, src);

              foreach (CompilerError ce in cr.Errors)
            {
              new Message(ce.ErrorText);
            }

              if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
            {
              Type ObjType = cr.CompiledAssembly.GetType("myclass");
              try
            {
              if (ObjType != null)
            {
              myobj = (MyClassBase)Activator.CreateInstance(ObjType);
              myobj.w = dimensions.Width;
              myobj.h = dimensions.Height;
            }
            }
              catch (Exception ex)
            {
              Console.WriteLine(ex.Message);
            }
              return true;
            }
              else
            return false;
        }
示例#23
0
        /// <summary>Processes a fractal, computing its values, returning a RenderedFractal.</summary>
        public RenderedFractal Process(IFractal fractal, Bounds boundsToRender, Dimensions imageDimensions)
        {
            width = imageDimensions.Width;
            height = imageDimensions.Height;

            PrecomputeValues(fractal, boundsToRender);

            var buffer = new float[width * height];

            Parallel.For(0, height, y =>
            {
                Parallel.For(0, width, x =>
                {
                    SetPoint(buffer, fractal, x, y);
                });
            });

            return new RenderedFractal(buffer, fractal.MaxIterations, boundsToRender, fractal);
        }
示例#24
0
 /// <summary>
 /// Converts the dimension value to a dimension symbol,
 /// for example, <c>True => 'T'</c>
 /// </summary>
 /// <param name="dimensionValue">Number that can be stored in the <c>IntersectionMatrix</c>.
 /// Possible values are <c>True, False, Dontcare, 0, 1, 2</c>.</param>
 /// <returns>Character for use in the string representation of an <c>IntersectionMatrix</c>.
 /// Possible values are <c>T, F, * , 0, 1, 2</c>.</returns>
 public static char ToDimensionSymbol(Dimensions dimensionValue)
 {
     switch (dimensionValue)
     {
         case Dimensions.False:
             return 'F';
         case Dimensions.True:
             return 'T';
         case Dimensions.Dontcare:
             return '*';
         case Dimensions.Point:
             return '0';
         case Dimensions.Curve:
             return '1';
         case Dimensions.Surface:
             return '2';
         default:
             throw new ArgumentOutOfRangeException
                 ("Unknown dimension value: " + dimensionValue);
     }
 }
        public static System.Drawing.Image ConstrainProportions(System.Drawing.Image imgPhoto, int Size, Dimensions Dimension)
        {
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;
            float nPercent = 0;

            switch (Dimension)
            {
                case Dimensions.Width:
                    nPercent = ((float)Size / (float)sourceWidth);
                    break;
                default:
                    nPercent = ((float)Size / (float)sourceHeight);
                    break;
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.CompositingQuality = CompositingQuality.HighQuality;
            grPhoto.SmoothingMode = SmoothingMode.HighQuality;
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
示例#26
0
        public void Init()
        {
            List<IParameters> ecoregionParms = new List<IParameters>();
            ecoregionParms.Add(new Parameters("eco0", "Ecoregion A", 0, true));
            ecoregionParms.Add(new Parameters("eco11", "Ecoregion B", 11, false));
            ecoregionParms.Add(new Parameters("eco222", "Ecoregion C", 222, true));
            ecoregionParms.Add(new Parameters("eco3333", "Ecoregion D", 3333, false));
            ecoregionParms.Add(new Parameters("eco-65535", "Ecoregion E", 65535, true));

            dataset = new Dataset(ecoregionParms);
            rasterDriverMgr = new RasterDriverManager();

            //  Initialize 8-bit ecoregion data
            ecoregions8Bit = new byte[,] {
                {   0,   0,  11, 222,  11 },
                {   0,  11,  11, 222,  11 },
                {   0,  11,  11, 222, 222 },
                {  11,  11,  11, 222, 222 },
                {  11,  11, 222, 222, 222 },
                {  11,  11, 222, 222, 222 }
            };
            dims8Bit = new Dimensions(ecoregions8Bit.GetLength(0),
                                      ecoregions8Bit.GetLength(1));
            rasterDriverMgr.SetData(path8Bit, ecoregions8Bit);

            //  Initialize 16-bit ecoregion data
            ecoregions16Bit = new ushort[,] {
                {   0,   0,  11, 222,  11,  3333,     0 },
                {   0,  11,  11, 222,  11,  3333, 65535 },
                {   0,  11,  11, 222, 222,  3333, 65535 },
                {  11,  11,  11, 222, 222,  3333, 65535 },
                {  11,  11, 222, 222, 222,  3333, 65535 },
                {  11,  11, 222, 222, 222, 65535, 65535 },
                {   0,   0, 222, 222, 222, 65535, 65535 }
            };
            dims16Bit = new Dimensions(ecoregions16Bit.GetLength(0),
                                       ecoregions16Bit.GetLength(1));
            rasterDriverMgr.SetData(path16Bit, ecoregions16Bit);
        }
示例#27
0
        public Image ConstrainProportions(Image imgPhoto, int Size, Dimensions Dimension)
        {
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;
            float nPercent = 0;

            switch (Dimension)
            {
                case Dimensions.Width:
                    nPercent = ((float)Size / (float)sourceWidth);
                    break;
                default:
                    nPercent = ((float)Size / (float)sourceHeight);
                    break;
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format32bppArgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            GraphicsUnit.Pixel);

            grPhoto.Dispose();
            //OnSharpen
            //if (destWidth < 168) BitmapFilter.Sharpen(bmPhoto, 14);
            return bmPhoto;
        }
		//---------------------------------------------------------------------

		public IOutputRaster Create(string        path,
				                    Dimensions    dimensions,
				                    System.Type[] bandTypes)
		{
			//  Use extension of the file to determine the raster format.
			string fileExt = System.IO.Path.GetExtension(path);
			string driverName;
			if (! extensionDriverDict.TryGetValue(fileExt, out driverName))
				throw new System.ApplicationException("Unknown file extension");
			Driver driver = DriverManager.GetDriverByName(driverName);

			if (driver.HasCreate) {
				//  TODO:  GDAL requires (assumes?) that all the bands are the
				//	same type (don't why).  So we should make sure the array
				//  has all the same type.
				PixelType pixelType = PixelType.Get(bandTypes[0]);
				Dataset dataset = driver.Create(path,
				                                dimensions.Columns,
				                                dimensions.Rows,
											    bandTypes.Length,
												pixelType.GDALType,
												null); //  string[] parmList
				if (null == dataset)
					return null;
				return new OutputRaster(dataset);
			}

			else if (driver.HasCreateCopy) {
				//  TODO: Maybe create an in-memory dataset first, and then
				//  pass that dataset to the driver's CreateCopy method.
				return null;
			}

			else
				//  Format doesn't support writing.
				//  TODO:  Maybe throw an exception to indicate that?
				return null;
		}
        public static Image ConstrainProportions(Image imgPhoto, int Size, Dimensions dimension)
        {
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;

            float nPercent = 0;

            switch (dimension)
            {
                case Dimensions.Width:
                    nPercent = ((float)Size / (float)sourceWidth);
                    break;
                default:
                    nPercent = ((float)Size / (float)sourceHeight);
                    break;
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);
            Size nSize = new Size(destWidth, destHeight);

            Image bmPhoto = new Bitmap(nSize.Width, nSize.Height);
            //bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(new Point(0, 0), nSize),
                new Rectangle(new Point(0, 0), imgPhoto.Size),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
示例#30
0
        public static Image ConstrainProportions(Image imgPhoto, int Size, Dimensions Dimension)
        {
            var sourceWidth = imgPhoto.Width;
            var sourceHeight = imgPhoto.Height;
            var sourceX = 0;
            var sourceY = 0;
            var destX = 0;
            var destY = 0;
            double nPercent = 0;

            switch (Dimension)
            {
                case Dimensions.Width:
                    nPercent = (Size / (double)sourceWidth);
                    break;
                default:
                    nPercent = (Size / (double)sourceHeight);
                    break;
            }

            var destWidth = (int)(sourceWidth * nPercent + 0.5);
            var destHeight = (int)(sourceHeight * nPercent + 0.5);

            var bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format32bppArgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            bmPhoto.MakeTransparent();
            var grPhoto = System.Drawing.Graphics.FromImage(bmPhoto);
            grPhoto.Clear(Color.Transparent);
            grPhoto.SmoothingMode = SmoothingMode.HighQuality;
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
示例#31
0
        public void ChangePrice_PriceBiggerThanPrevious_PriceUpdated()
        {
            // arrange
            var provider          = Provider.MakeProvider("Julio", "09883060000174");
            var providerOrder     = ProviderOrder.MakeProviderOrder(7, provider);
            var product           = Product.MakeProduct("Test product", "Test product", 15, Dimensions.MakeDimensions(11, 12, 13));
            var providerOrderItem = ProviderOrderItem.MakeProviderOrderItem(providerOrder, product, 5);

            // act
            providerOrderItem.ChangePrice(20);

            // assert
            Assert.Equal(providerOrderItem.Amount, 5);
            Assert.Equal(providerOrderItem.Deposits.Count, 1);
            Assert.Equal(providerOrderItem.Price, 20);
            Assert.Equal(providerOrderItem.TotalValue, 100);
            Assert.Equal(providerOrder.TotalValue, 100);
            Assert.Equal(product.Amount, 5);
        }
示例#32
0
        public void DeleteProviderOrderItem_ValidParameters_ProviderOrderItemDeleted()
        {
            // arrange
            var provider          = Provider.MakeProvider("Julio", "09883060000174");
            var providerOrder     = ProviderOrder.MakeProviderOrder(7, provider);
            var product           = Product.MakeProduct("Test product", "Test product", 15, Dimensions.MakeDimensions(11, 12, 13));
            var providerOrderItem = ProviderOrderItem.MakeProviderOrderItem(providerOrder, product, 5);

            //act
            providerOrderItem.Delete();

            // assert
            Assert.True(providerOrderItem.IsDeleted);
        }
示例#33
0
        /// <summary>Creates a metadata sidecar for an optical disc (e.g. CD, DVD, GD, BD, XGD, GOD)</summary>
        /// <param name="image">Image</param>
        /// <param name="filterId">Filter uuid</param>
        /// <param name="imagePath">Image path</param>
        /// <param name="fi">Image file information</param>
        /// <param name="plugins">Image plugins</param>
        /// <param name="imgChecksums">List of image checksums</param>
        /// <param name="sidecar">Metadata sidecar</param>
        void OpticalDisc(IOpticalMediaImage image, Guid filterId, string imagePath, FileInfo fi, PluginBase plugins,
                         List <ChecksumType> imgChecksums, ref CICMMetadataType sidecar, Encoding encoding)
        {
            if (aborted)
            {
                return;
            }

            sidecar.OpticalDisc = new[]
            {
                new OpticalDiscType
                {
                    Checksums = imgChecksums.ToArray(), Image = new ImageType
                    {
                        format = image.Format, offset = 0, offsetSpecified = true, Value = Path.GetFileName(imagePath)
                    },
                    Size = (ulong)fi.Length, Sequence = new SequenceType
                    {
                        MediaTitle = image.Info.MediaTitle
                    }
                }
            };

            if (image.Info.MediaSequence != 0 &&
                image.Info.LastMediaSequence != 0)
            {
                sidecar.OpticalDisc[0].Sequence.MediaSequence = (uint)image.Info.MediaSequence;
                sidecar.OpticalDisc[0].Sequence.TotalMedia    = (uint)image.Info.LastMediaSequence;
            }
            else
            {
                sidecar.OpticalDisc[0].Sequence.MediaSequence = 1;
                sidecar.OpticalDisc[0].Sequence.TotalMedia    = 1;
            }

            MediaType dskType = image.Info.MediaType;

            UpdateStatus("Hashing media tags...");

            foreach (MediaTagType tagType in image.Info.ReadableMediaTags)
            {
                if (aborted)
                {
                    return;
                }

                switch (tagType)
                {
                case MediaTagType.CD_ATIP:
                    sidecar.OpticalDisc[0].ATIP = new DumpType
                    {
                        Image     = Path.GetFileName(imagePath),
                        Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.CD_ATIP)).ToArray(),
                        Size      = (ulong)image.ReadDiskTag(MediaTagType.CD_ATIP).Length
                    };

                    ATIP.CDATIP?atip = ATIP.Decode(image.ReadDiskTag(MediaTagType.CD_ATIP));

                    if (atip.HasValue)
                    {
                        if (atip.Value.DDCD)
                        {
                            dskType = atip.Value.DiscType ? MediaType.DDCDRW : MediaType.DDCDR;
                        }
                        else
                        {
                            dskType = atip.Value.DiscType ? MediaType.CDRW : MediaType.CDR;
                        }
                    }

                    break;

                case MediaTagType.DVD_BCA:
                    sidecar.OpticalDisc[0].BCA = new DumpType
                    {
                        Image     = Path.GetFileName(imagePath),
                        Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.DVD_BCA)).ToArray(),
                        Size      = (ulong)image.ReadDiskTag(MediaTagType.DVD_BCA).Length
                    };

                    break;

                case MediaTagType.BD_BCA:
                    sidecar.OpticalDisc[0].BCA = new DumpType
                    {
                        Image     = Path.GetFileName(imagePath),
                        Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.BD_BCA)).ToArray(),
                        Size      = (ulong)image.ReadDiskTag(MediaTagType.BD_BCA).Length
                    };

                    break;

                case MediaTagType.DVD_CMI:
                    sidecar.OpticalDisc[0].CMI = new DumpType
                    {
                        Image     = Path.GetFileName(imagePath),
                        Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.DVD_CMI)).ToArray(),
                        Size      = (ulong)image.ReadDiskTag(MediaTagType.DVD_CMI).Length
                    };

                    CSS_CPRM.LeadInCopyright?cmi =
                        CSS_CPRM.DecodeLeadInCopyright(image.ReadDiskTag(MediaTagType.DVD_CMI));

                    if (cmi.HasValue)
                    {
                        switch (cmi.Value.CopyrightType)
                        {
                        case CopyrightType.AACS:
                            sidecar.OpticalDisc[0].CopyProtection = "AACS";

                            break;

                        case CopyrightType.CSS:
                            sidecar.OpticalDisc[0].CopyProtection = "CSS";

                            break;

                        case CopyrightType.CPRM:
                            sidecar.OpticalDisc[0].CopyProtection = "CPRM";

                            break;
                        }
                    }

                    break;

                case MediaTagType.DVD_DMI:
                    sidecar.OpticalDisc[0].DMI = new DumpType
                    {
                        Image     = Path.GetFileName(imagePath),
                        Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.DVD_DMI)).ToArray(),
                        Size      = (ulong)image.ReadDiskTag(MediaTagType.DVD_DMI).Length
                    };

                    if (DMI.IsXbox(image.ReadDiskTag(MediaTagType.DVD_DMI)))
                    {
                        dskType = MediaType.XGD;

                        sidecar.OpticalDisc[0].Dimensions = new DimensionsType
                        {
                            Diameter = 120, Thickness = 1.2
                        };
                    }
                    else if (DMI.IsXbox360(image.ReadDiskTag(MediaTagType.DVD_DMI)))
                    {
                        dskType = MediaType.XGD2;

                        sidecar.OpticalDisc[0].Dimensions = new DimensionsType
                        {
                            Diameter = 120, Thickness = 1.2
                        };
                    }

                    break;

                case MediaTagType.DVD_PFI:
                    sidecar.OpticalDisc[0].PFI = new DumpType
                    {
                        Image     = Path.GetFileName(imagePath),
                        Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.DVD_PFI)).ToArray(),
                        Size      = (ulong)image.ReadDiskTag(MediaTagType.DVD_PFI).Length
                    };

                    PFI.PhysicalFormatInformation?pfi = PFI.Decode(image.ReadDiskTag(MediaTagType.DVD_PFI));

                    if (pfi.HasValue)
                    {
                        if (dskType != MediaType.XGD &&
                            dskType != MediaType.XGD2 &&
                            dskType != MediaType.XGD3 &&
                            dskType != MediaType.PS2DVD &&
                            dskType != MediaType.PS3DVD &&
                            dskType != MediaType.Nuon)
                        {
                            switch (pfi.Value.DiskCategory)
                            {
                            case DiskCategory.DVDPR:
                                dskType = MediaType.DVDPR;

                                break;

                            case DiskCategory.DVDPRDL:
                                dskType = MediaType.DVDPRDL;

                                break;

                            case DiskCategory.DVDPRW:
                                dskType = MediaType.DVDPRW;

                                break;

                            case DiskCategory.DVDPRWDL:
                                dskType = MediaType.DVDPRWDL;

                                break;

                            case DiskCategory.DVDR:
                                dskType = MediaType.DVDR;

                                break;

                            case DiskCategory.DVDRAM:
                                dskType = MediaType.DVDRAM;

                                break;

                            case DiskCategory.DVDROM:
                                dskType = MediaType.DVDROM;

                                break;

                            case DiskCategory.DVDRW:
                                dskType = MediaType.DVDRW;

                                break;

                            case DiskCategory.HDDVDR:
                                dskType = MediaType.HDDVDR;

                                break;

                            case DiskCategory.HDDVDRAM:
                                dskType = MediaType.HDDVDRAM;

                                break;

                            case DiskCategory.HDDVDROM:
                                dskType = MediaType.HDDVDROM;

                                break;

                            case DiskCategory.HDDVDRW:
                                dskType = MediaType.HDDVDRW;

                                break;

                            case DiskCategory.Nintendo:
                                dskType = MediaType.GOD;

                                break;

                            case DiskCategory.UMD:
                                dskType = MediaType.UMD;

                                break;
                            }

                            if (dskType == MediaType.DVDR &&
                                pfi.Value.PartVersion == 6)
                            {
                                dskType = MediaType.DVDRDL;
                            }

                            if (dskType == MediaType.DVDRW &&
                                pfi.Value.PartVersion == 3)
                            {
                                dskType = MediaType.DVDRWDL;
                            }

                            if (dskType == MediaType.GOD &&
                                pfi.Value.DiscSize == DVDSize.OneTwenty)
                            {
                                dskType = MediaType.WOD;
                            }

                            sidecar.OpticalDisc[0].Dimensions = new DimensionsType();

                            if (dskType == MediaType.UMD)
                            {
                                sidecar.OpticalDisc[0].Dimensions.Height          = 64;
                                sidecar.OpticalDisc[0].Dimensions.HeightSpecified = true;
                                sidecar.OpticalDisc[0].Dimensions.Width           = 63;
                                sidecar.OpticalDisc[0].Dimensions.WidthSpecified  = true;
                                sidecar.OpticalDisc[0].Dimensions.Thickness       = 4;
                            }
                            else
                            {
                                switch (pfi.Value.DiscSize)
                                {
                                case DVDSize.Eighty:
                                    sidecar.OpticalDisc[0].Dimensions.Diameter          = 80;
                                    sidecar.OpticalDisc[0].Dimensions.DiameterSpecified = true;
                                    sidecar.OpticalDisc[0].Dimensions.Thickness         = 1.2;

                                    break;

                                case DVDSize.OneTwenty:
                                    sidecar.OpticalDisc[0].Dimensions.Diameter          = 120;
                                    sidecar.OpticalDisc[0].Dimensions.DiameterSpecified = true;
                                    sidecar.OpticalDisc[0].Dimensions.Thickness         = 1.2;

                                    break;
                                }
                            }
                        }
                    }

                    break;

                case MediaTagType.CD_PMA:
                    sidecar.OpticalDisc[0].PMA = new DumpType
                    {
                        Image     = Path.GetFileName(imagePath),
                        Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.CD_PMA)).ToArray(),
                        Size      = (ulong)image.ReadDiskTag(MediaTagType.CD_PMA).Length
                    };

                    break;

                case MediaTagType.CD_FullTOC:
                    sidecar.OpticalDisc[0].TOC = new DumpType
                    {
                        Image     = Path.GetFileName(imagePath),
                        Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.CD_FullTOC)).ToArray(),
                        Size      = (ulong)image.ReadDiskTag(MediaTagType.CD_FullTOC).Length
                    };

                    break;

                case MediaTagType.CD_FirstTrackPregap:
                    sidecar.OpticalDisc[0].FirstTrackPregrap = new[]
                    {
                        new BorderType
                        {
                            Image     = Path.GetFileName(imagePath),
                            Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.CD_FirstTrackPregap)).
                                        ToArray(),
                            Size = (ulong)image.ReadDiskTag(MediaTagType.CD_FirstTrackPregap).Length
                        }
                    };

                    break;

                case MediaTagType.CD_LeadIn:
                    sidecar.OpticalDisc[0].LeadIn = new[]
                    {
                        new BorderType
                        {
                            Image     = Path.GetFileName(imagePath),
                            Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.CD_LeadIn)).ToArray(),
                            Size      = (ulong)image.ReadDiskTag(MediaTagType.CD_LeadIn).Length
                        }
                    };

                    break;

                case MediaTagType.Xbox_SecuritySector:
                    if (sidecar.OpticalDisc[0].Xbox == null)
                    {
                        sidecar.OpticalDisc[0].Xbox = new XboxType();
                    }

                    sidecar.OpticalDisc[0].Xbox.SecuritySectors = new[]
                    {
                        new XboxSecuritySectorsType
                        {
                            RequestNumber = 0, RequestVersion = 1, SecuritySectors = new DumpType
                            {
                                Image     = Path.GetFileName(imagePath),
                                Checksums = Checksum.
                                            GetChecksums(image.ReadDiskTag(MediaTagType.Xbox_SecuritySector)).
                                            ToArray(),
                                Size = (ulong)image.ReadDiskTag(MediaTagType.Xbox_SecuritySector).Length
                            }
                        }
                    };

                    break;

                case MediaTagType.Xbox_PFI:
                    if (sidecar.OpticalDisc[0].Xbox == null)
                    {
                        sidecar.OpticalDisc[0].Xbox = new XboxType();
                    }

                    sidecar.OpticalDisc[0].Xbox.PFI = new DumpType
                    {
                        Image     = Path.GetFileName(imagePath),
                        Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.Xbox_PFI)).ToArray(),
                        Size      = (ulong)image.ReadDiskTag(MediaTagType.Xbox_PFI).Length
                    };

                    break;

                case MediaTagType.Xbox_DMI:
                    if (sidecar.OpticalDisc[0].Xbox == null)
                    {
                        sidecar.OpticalDisc[0].Xbox = new XboxType();
                    }

                    sidecar.OpticalDisc[0].Xbox.DMI = new DumpType
                    {
                        Image     = Path.GetFileName(imagePath),
                        Checksums = Checksum.GetChecksums(image.ReadDiskTag(MediaTagType.Xbox_DMI)).ToArray(),
                        Size      = (ulong)image.ReadDiskTag(MediaTagType.Xbox_DMI).Length
                    };

                    break;
                }
            }

            try
            {
                List <Session> sessions = image.Sessions;
                sidecar.OpticalDisc[0].Sessions = (uint)(sessions?.Count ?? 1);
            }
            catch
            {
                sidecar.OpticalDisc[0].Sessions = 1;
            }

            List <Track>     tracks  = image.Tracks;
            List <TrackType> trksLst = null;

            if (tracks != null)
            {
                sidecar.OpticalDisc[0].Tracks    = new uint[1];
                sidecar.OpticalDisc[0].Tracks[0] = (uint)tracks.Count;
                trksLst = new List <TrackType>();
            }

            if (sidecar.OpticalDisc[0].Dimensions == null &&
                image.Info.MediaType != MediaType.Unknown)
            {
                sidecar.OpticalDisc[0].Dimensions = Dimensions.DimensionsFromMediaType(image.Info.MediaType);
            }

            if (aborted)
            {
                return;
            }

            InitProgress();

            UpdateStatus("Checking filesystems");
            List <Partition> partitions = Partitions.GetAll(image);

            Partitions.AddSchemesToStats(partitions);

            UpdateStatus("Hashing tracks...");

            foreach (Track trk in tracks)
            {
                if (aborted)
                {
                    EndProgress();

                    return;
                }

                var xmlTrk = new TrackType();

                switch (trk.TrackType)
                {
                case CommonTypes.Enums.TrackType.Audio:
                    xmlTrk.TrackType1 = TrackTypeTrackType.audio;

                    break;

                case CommonTypes.Enums.TrackType.CdMode2Form2:
                    xmlTrk.TrackType1 = TrackTypeTrackType.m2f2;

                    break;

                case CommonTypes.Enums.TrackType.CdMode2Formless:
                    xmlTrk.TrackType1 = TrackTypeTrackType.mode2;

                    break;

                case CommonTypes.Enums.TrackType.CdMode2Form1:
                    xmlTrk.TrackType1 = TrackTypeTrackType.m2f1;

                    break;

                case CommonTypes.Enums.TrackType.CdMode1:
                    xmlTrk.TrackType1 = TrackTypeTrackType.mode1;

                    break;

                case CommonTypes.Enums.TrackType.Data:
                    switch (sidecar.OpticalDisc[0].DiscType)
                    {
                    case "BD":
                        xmlTrk.TrackType1 = TrackTypeTrackType.bluray;

                        break;

                    case "DDCD":
                        xmlTrk.TrackType1 = TrackTypeTrackType.ddcd;

                        break;

                    case "DVD":
                        xmlTrk.TrackType1 = TrackTypeTrackType.dvd;

                        break;

                    case "HD DVD":
                        xmlTrk.TrackType1 = TrackTypeTrackType.hddvd;

                        break;

                    default:
                        xmlTrk.TrackType1 = TrackTypeTrackType.mode1;

                        break;
                    }

                    break;
                }

                xmlTrk.Sequence = new TrackSequenceType
                {
                    Session = trk.TrackSession, TrackNumber = trk.TrackSequence
                };

                xmlTrk.StartSector = trk.TrackStartSector;
                xmlTrk.EndSector   = trk.TrackEndSector;

                if (trk.Indexes != null &&
                    trk.Indexes.ContainsKey(0))
                {
                    if (trk.Indexes.TryGetValue(0, out ulong idx0))
                    {
                        xmlTrk.StartSector = idx0;
                    }
                }

                switch (sidecar.OpticalDisc[0].DiscType)
                {
                case "CD":
                case "GD":
                    xmlTrk.StartMSF = LbaToMsf((long)xmlTrk.StartSector);
                    xmlTrk.EndMSF   = LbaToMsf((long)xmlTrk.EndSector);

                    break;

                case "DDCD":
                    xmlTrk.StartMSF = DdcdLbaToMsf((long)xmlTrk.StartSector);
                    xmlTrk.EndMSF   = DdcdLbaToMsf((long)xmlTrk.EndSector);

                    break;
                }

                xmlTrk.Image = new ImageType
                {
                    Value = Path.GetFileName(trk.TrackFile), format = trk.TrackFileType
                };

                if (trk.TrackFileOffset > 0)
                {
                    xmlTrk.Image.offset          = trk.TrackFileOffset;
                    xmlTrk.Image.offsetSpecified = true;
                }

                xmlTrk.Size           = (xmlTrk.EndSector - xmlTrk.StartSector + 1) * (ulong)trk.TrackRawBytesPerSector;
                xmlTrk.BytesPerSector = (uint)trk.TrackBytesPerSector;

                uint  sectorsToRead = 512;
                ulong sectors       = xmlTrk.EndSector - xmlTrk.StartSector + 1;
                ulong doneSectors   = 0;

                // If there is only one track, and it's the same as the image file (e.g. ".iso" files), don't re-checksum.
                if (image.Id == new Guid("12345678-AAAA-BBBB-CCCC-123456789000") &&

                    // Only if filter is none...
                    (filterId == new Guid("12345678-AAAA-BBBB-CCCC-123456789000") ||

                     // ...or AppleDouble
                     filterId == new Guid("1b2165ee-c9df-4b21-bbbb-9e5892b2df4d")))
                {
                    xmlTrk.Checksums = sidecar.OpticalDisc[0].Checksums;
                }
                else
                {
                    UpdateProgress("Track {0} of {1}", trk.TrackSequence, tracks.Count);

                    // For fast debugging, skip checksum
                    //goto skipChecksum;

                    var trkChkWorker = new Checksum();

                    InitProgress2();

                    while (doneSectors < sectors)
                    {
                        if (aborted)
                        {
                            EndProgress();
                            EndProgress2();

                            return;
                        }

                        byte[] sector;

                        if (sectors - doneSectors >= sectorsToRead)
                        {
                            sector = image.ReadSectorsLong(doneSectors, sectorsToRead, xmlTrk.Sequence.TrackNumber);

                            UpdateProgress2("Hashings sector {0} of {1}", (long)doneSectors,
                                            (long)(trk.TrackEndSector - trk.TrackStartSector + 1));

                            doneSectors += sectorsToRead;
                        }
                        else
                        {
                            sector = image.ReadSectorsLong(doneSectors, (uint)(sectors - doneSectors),
                                                           xmlTrk.Sequence.TrackNumber);

                            UpdateProgress2("Hashings sector {0} of {1}", (long)doneSectors,
                                            (long)(trk.TrackEndSector - trk.TrackStartSector + 1));

                            doneSectors += sectors - doneSectors;
                        }

                        trkChkWorker.Update(sector);
                    }

                    List <ChecksumType> trkChecksums = trkChkWorker.End();

                    xmlTrk.Checksums = trkChecksums.ToArray();

                    EndProgress2();
                }

                if (trk.TrackSubchannelType != TrackSubchannelType.None)
                {
                    xmlTrk.SubChannel = new SubChannelType
                    {
                        Image = new ImageType
                        {
                            Value = trk.TrackSubchannelFile
                        },

                        // TODO: Packed subchannel has different size?
                        Size = (xmlTrk.EndSector - xmlTrk.StartSector + 1) * 96
                    };

                    switch (trk.TrackSubchannelType)
                    {
                    case TrackSubchannelType.Packed:
                    case TrackSubchannelType.PackedInterleaved:
                        xmlTrk.SubChannel.Image.format = "rw";

                        break;

                    case TrackSubchannelType.Raw:
                    case TrackSubchannelType.RawInterleaved:
                        xmlTrk.SubChannel.Image.format = "rw_raw";

                        break;

                    case TrackSubchannelType.Q16:
                    case TrackSubchannelType.Q16Interleaved:
                        xmlTrk.SubChannel.Image.format = "q16";

                        break;
                    }

                    if (trk.TrackFileOffset > 0)
                    {
                        xmlTrk.SubChannel.Image.offset          = trk.TrackSubchannelOffset;
                        xmlTrk.SubChannel.Image.offsetSpecified = true;
                    }

                    var subChkWorker = new Checksum();

                    sectors     = xmlTrk.EndSector - xmlTrk.StartSector + 1;
                    doneSectors = 0;

                    InitProgress2();

                    while (doneSectors < sectors)
                    {
                        if (aborted)
                        {
                            EndProgress();
                            EndProgress2();

                            return;
                        }

                        byte[] sector;

                        if (sectors - doneSectors >= sectorsToRead)
                        {
                            sector = image.ReadSectorsTag(doneSectors, sectorsToRead, xmlTrk.Sequence.TrackNumber,
                                                          SectorTagType.CdSectorSubchannel);

                            UpdateProgress2("Hashings subchannel sector {0} of {1}", (long)doneSectors,
                                            (long)(trk.TrackEndSector - trk.TrackStartSector + 1));

                            doneSectors += sectorsToRead;
                        }
                        else
                        {
                            sector = image.ReadSectorsTag(doneSectors, (uint)(sectors - doneSectors),
                                                          xmlTrk.Sequence.TrackNumber,
                                                          SectorTagType.CdSectorSubchannel);

                            UpdateProgress2("Hashings subchannel sector {0} of {1}", (long)doneSectors,
                                            (long)(trk.TrackEndSector - trk.TrackStartSector + 1));

                            doneSectors += sectors - doneSectors;
                        }

                        subChkWorker.Update(sector);
                    }

                    List <ChecksumType> subChecksums = subChkWorker.End();

                    xmlTrk.SubChannel.Checksums = subChecksums.ToArray();

                    EndProgress2();
                }

                // For fast debugging, skip checksum
                //skipChecksum:

                List <Partition> trkPartitions = partitions.
                                                 Where(p => p.Start >= trk.TrackStartSector &&
                                                       p.End <= trk.TrackEndSector).ToList();

                xmlTrk.FileSystemInformation = new PartitionType[1];

                if (trkPartitions.Count > 0)
                {
                    xmlTrk.FileSystemInformation = new PartitionType[trkPartitions.Count];

                    for (int i = 0; i < trkPartitions.Count; i++)
                    {
                        xmlTrk.FileSystemInformation[i] = new PartitionType
                        {
                            Description = trkPartitions[i].Description, EndSector = trkPartitions[i].End,
                            Name        = trkPartitions[i].Name, Sequence = (uint)trkPartitions[i].Sequence,
                            StartSector = trkPartitions[i].Start, Type = trkPartitions[i].Type
                        };

                        List <FileSystemType> lstFs = new List <FileSystemType>();

                        foreach (IFilesystem plugin in plugins.PluginsList.Values)
                        {
                            try
                            {
                                if (aborted)
                                {
                                    EndProgress();

                                    return;
                                }

                                if (!plugin.Identify(image, trkPartitions[i]))
                                {
                                    continue;
                                }

                                plugin.GetInformation(image, trkPartitions[i], out _, encoding);
                                lstFs.Add(plugin.XmlFsType);
                                Statistics.AddFilesystem(plugin.XmlFsType.Type);

                                switch (plugin.XmlFsType.Type)
                                {
                                case "Opera":
                                    dskType = MediaType.ThreeDO;

                                    break;

                                case "PC Engine filesystem":
                                    dskType = MediaType.SuperCDROM2;

                                    break;

                                case "Nintendo Wii filesystem":
                                    dskType = MediaType.WOD;

                                    break;

                                case "Nintendo Gamecube filesystem":
                                    dskType = MediaType.GOD;

                                    break;
                                }
                            }
                        }
示例#34
0
        public void DeleteProviderOrder_DeletedProviderOrder_ExceptionThrown()
        {
            // arrange
            var provider      = Provider.MakeProvider("Julio", "09883060000174");
            var providerOrder = ProviderOrder.MakeProviderOrder(7, provider);
            var product       = Product.MakeProduct("Test product", "Test product", 15, Dimensions.MakeDimensions(11, 12, 13));

            product.UpdateAmount(50);
            var providerOrderItem = ProviderOrderItem.MakeProviderOrderItem(providerOrder, product, 5);

            providerOrderItem.Delete();

            // act
            Assert.Throws <InvalidOperationException>(() => providerOrderItem.Delete());
        }
示例#35
0
        /// <summary>
        ///     Dumps a MultiMediaCard or SecureDigital flash card
        /// </summary>
        /// <param name="dev">Device</param>
        /// <param name="devicePath">Path to the device</param>
        /// <param name="outputPrefix">Prefix for output data files</param>
        /// <param name="outputPlugin">Plugin for output file</param>
        /// <param name="retryPasses">How many times to retry</param>
        /// <param name="force">Force to continue dump whenever possible</param>
        /// <param name="dumpRaw">Dump long or scrambled sectors</param>
        /// <param name="persistent">Store whatever data the drive returned on error</param>
        /// <param name="stopOnError">Stop dump on first error</param>
        /// <param name="resume">Information for dump resuming</param>
        /// <param name="dumpLog">Dump logger</param>
        /// <param name="encoding">Encoding to use when analyzing dump</param>
        /// <param name="outputPath">Path to output file</param>
        /// <param name="formatOptions">Formats to pass to output file plugin</param>
        /// <exception cref="ArgumentException">If you asked to dump long sectors from a SCSI Streaming device</exception>
        public static void Dump(Device dev, string devicePath,
                                IWritableImage outputPlugin, ushort retryPasses,
                                bool force, bool dumpRaw,
                                bool persistent, bool stopOnError, ref Resume resume,
                                ref DumpLog dumpLog, Encoding encoding,
                                string outputPrefix, string outputPath,
                                Dictionary <string, string> formatOptions, CICMMetadataType preSidecar,
                                uint skip,
                                bool nometadata, bool notrim)
        {
            bool aborted;

            if (dumpRaw)
            {
                DicConsole.ErrorWriteLine("Raw dumping is not supported in MultiMediaCard or SecureDigital devices.");

                if (force)
                {
                    DicConsole.ErrorWriteLine("Continuing...");
                }
                else
                {
                    DicConsole.ErrorWriteLine("Aborting...");
                    return;
                }
            }

            bool         sense;
            const ushort SD_PROFILE = 0x0001;
            const uint   TIMEOUT    = 5;
            double       duration;

            uint  blocksToRead = 128;
            uint  blockSize    = 512;
            ulong blocks       = 0;

            byte[] csd  = null;
            byte[] ocr  = null;
            byte[] ecsd = null;
            byte[] scr  = null;
            int    physicalBlockSize = 0;
            bool   byteAddressed     = true;

            Dictionary <MediaTagType, byte[]> mediaTags = new Dictionary <MediaTagType, byte[]>();

            switch (dev.Type)
            {
            case DeviceType.MMC:
            {
                dumpLog.WriteLine("Reading Extended CSD");
                sense = dev.ReadExtendedCsd(out ecsd, out _, TIMEOUT, out duration);
                if (!sense)
                {
                    ExtendedCSD ecsdDecoded = Decoders.MMC.Decoders.DecodeExtendedCSD(ecsd);
                    blocksToRead = ecsdDecoded.OptimalReadSize;
                    blocks       = ecsdDecoded.SectorCount;
                    blockSize    = (uint)(ecsdDecoded.SectorSize == 1 ? 4096 : 512);
                    if (ecsdDecoded.NativeSectorSize == 0)
                    {
                        physicalBlockSize = 512;
                    }
                    else if (ecsdDecoded.NativeSectorSize == 1)
                    {
                        physicalBlockSize = 4096;
                    }
                    // Supposing it's high-capacity MMC if it has Extended CSD...
                    byteAddressed = false;
                    mediaTags.Add(MediaTagType.MMC_ExtendedCSD, null);
                }
                else
                {
                    ecsd = null;
                }

                dumpLog.WriteLine("Reading CSD");
                sense = dev.ReadCsd(out csd, out _, TIMEOUT, out duration);
                if (!sense)
                {
                    if (blocks == 0)
                    {
                        CSD csdDecoded = Decoders.MMC.Decoders.DecodeCSD(csd);
                        blocks    = (ulong)((csdDecoded.Size + 1) * Math.Pow(2, csdDecoded.SizeMultiplier + 2));
                        blockSize = (uint)Math.Pow(2, csdDecoded.ReadBlockLength);
                    }

                    mediaTags.Add(MediaTagType.MMC_CSD, null);
                }
                else
                {
                    csd = null;
                }

                dumpLog.WriteLine("Reading OCR");
                sense = dev.ReadOcr(out ocr, out _, TIMEOUT, out duration);
                if (sense)
                {
                    ocr = null;
                }
                else
                {
                    mediaTags.Add(MediaTagType.MMC_OCR, null);
                }

                break;
            }

            case DeviceType.SecureDigital:
            {
                dumpLog.WriteLine("Reading CSD");
                sense = dev.ReadCsd(out csd, out _, TIMEOUT, out duration);
                if (!sense)
                {
                    Decoders.SecureDigital.CSD csdDecoded = Decoders.SecureDigital.Decoders.DecodeCSD(csd);
                    blocks = (ulong)(csdDecoded.Structure == 0
                                             ? (csdDecoded.Size + 1) * Math.Pow(2, csdDecoded.SizeMultiplier + 2)
                                             : (csdDecoded.Size + 1) * 1024);
                    blockSize = (uint)Math.Pow(2, csdDecoded.ReadBlockLength);
                    // Structure >=1 for SDHC/SDXC, so that's block addressed
                    byteAddressed = csdDecoded.Structure == 0;
                    mediaTags.Add(MediaTagType.SD_CSD, null);
                }
                else
                {
                    csd = null;
                }

                dumpLog.WriteLine("Reading OCR");
                sense = dev.ReadSdocr(out ocr, out _, TIMEOUT, out duration);
                if (sense)
                {
                    ocr = null;
                }
                else
                {
                    mediaTags.Add(MediaTagType.SD_OCR, null);
                }

                dumpLog.WriteLine("Reading SCR");
                sense = dev.ReadScr(out scr, out _, TIMEOUT, out duration);
                if (sense)
                {
                    scr = null;
                }
                else
                {
                    mediaTags.Add(MediaTagType.SD_SCR, null);
                }

                break;
            }
            }

            dumpLog.WriteLine("Reading CID");
            sense = dev.ReadCid(out byte[] cid, out _, TIMEOUT, out duration);
            if (sense)
            {
                cid = null;
            }
            else
            {
                mediaTags.Add(dev.Type == DeviceType.SecureDigital ? MediaTagType.SD_CID : MediaTagType.MMC_CID, null);
            }

            DateTime start;
            DateTime end;
            double   totalDuration = 0;
            double   currentSpeed  = 0;
            double   maxSpeed      = double.MinValue;
            double   minSpeed      = double.MaxValue;

            aborted = false;
            System.Console.CancelKeyPress += (sender, e) => e.Cancel = aborted = true;

            if (blocks == 0)
            {
                dumpLog.WriteLine("Cannot get device size.");
                DicConsole.ErrorWriteLine("Unable to get device size.");
                return;
            }

            dumpLog.WriteLine("Device reports {0} blocks.", blocks);

            byte[] cmdBuf;
            bool   error;

            while (true)
            {
                error = dev.Read(out cmdBuf, out _, 0, blockSize, blocksToRead, byteAddressed, TIMEOUT, out duration);

                if (error)
                {
                    blocksToRead /= 2;
                }

                if (!error || blocksToRead == 1)
                {
                    break;
                }
            }

            if (error)
            {
                dumpLog.WriteLine("ERROR: Cannot get blocks to read, device error {0}.", dev.LastError);
                DicConsole.ErrorWriteLine("Device error {0} trying to guess ideal transfer length.", dev.LastError);
                return;
            }

            dumpLog.WriteLine("Device can read {0} blocks at a time.", blocksToRead);

            if (skip < blocksToRead)
            {
                skip = blocksToRead;
            }

            DumpHardwareType currentTry = null;
            ExtentsULong     extents    = null;

            ResumeSupport.Process(true, false, blocks, dev.Manufacturer, dev.Model, dev.Serial, dev.PlatformId,
                                  ref resume, ref currentTry, ref extents);
            if (currentTry == null || extents == null)
            {
                throw new InvalidOperationException("Could not process resume file, not continuing...");
            }

            bool ret = true;

            foreach (MediaTagType tag in mediaTags.Keys)
            {
                if (outputPlugin.SupportedMediaTags.Contains(tag))
                {
                    continue;
                }

                ret = false;
                dumpLog.WriteLine($"Output format does not support {tag}.");
                DicConsole.ErrorWriteLine($"Output format does not support {tag}.");
            }

            if (!ret)
            {
                dumpLog.WriteLine("Several media tags not supported, {0}continuing...", force ? "" : "not ");
                DicConsole.ErrorWriteLine("Several media tags not supported, {0}continuing...", force ? "" : "not ");
                if (!force)
                {
                    return;
                }
            }

            DicConsole.WriteLine("Reading {0} sectors at a time.", blocksToRead);

            MhddLog mhddLog = new MhddLog(outputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead);
            IbgLog  ibgLog  = new IbgLog(outputPrefix + ".ibg", SD_PROFILE);

            ret = outputPlugin.Create(outputPath,
                                      dev.Type == DeviceType.SecureDigital ? MediaType.SecureDigital : MediaType.MMC,
                                      formatOptions, blocks, blockSize);

            // Cannot create image
            if (!ret)
            {
                dumpLog.WriteLine("Error creating output image, not continuing.");
                dumpLog.WriteLine(outputPlugin.ErrorMessage);
                DicConsole.ErrorWriteLine("Error creating output image, not continuing.");
                DicConsole.ErrorWriteLine(outputPlugin.ErrorMessage);
                return;
            }

            if (resume.NextBlock > 0)
            {
                dumpLog.WriteLine("Resuming from block {0}.", resume.NextBlock);
            }

            start = DateTime.UtcNow;
            double imageWriteDuration = 0;
            bool   newTrim            = false;

            for (ulong i = resume.NextBlock; i < blocks; i += blocksToRead)
            {
                if (aborted)
                {
                    currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                    dumpLog.WriteLine("Aborted!");
                    break;
                }

                if (blocks - i < blocksToRead)
                {
                    blocksToRead = (byte)(blocks - i);
                }

                #pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator
                if (currentSpeed > maxSpeed && currentSpeed != 0)
                {
                    maxSpeed = currentSpeed;
                }
                if (currentSpeed < minSpeed && currentSpeed != 0)
                {
                    minSpeed = currentSpeed;
                }
                #pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator

                DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed);

                error = dev.Read(out cmdBuf, out _, (uint)i, blockSize, blocksToRead, byteAddressed, TIMEOUT,
                                 out duration);

                if (!error)
                {
                    mhddLog.Write(i, duration);
                    ibgLog.Write(i, currentSpeed * 1024);
                    DateTime writeStart = DateTime.Now;
                    outputPlugin.WriteSectors(cmdBuf, i, blocksToRead);
                    imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds;
                    extents.Add(i, blocksToRead, true);
                }
                else
                {
                    if (i + skip > blocks)
                    {
                        skip = (uint)(blocks - i);
                    }

                    for (ulong b = i; b < i + skip; b++)
                    {
                        resume.BadBlocks.Add(b);
                    }

                    mhddLog.Write(i, duration < 500 ? 65535 : duration);

                    ibgLog.Write(i, 0);
                    DateTime writeStart = DateTime.Now;
                    outputPlugin.WriteSectors(new byte[blockSize * skip], i, skip);
                    imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds;
                    dumpLog.WriteLine("Skipping {0} blocks from errored block {1}.", skip, i);
                    i      += skip - blocksToRead;
                    newTrim = true;
                }

                double newSpeed =
                    (double)blockSize * blocksToRead / 1048576 / (duration / 1000);
                if (!double.IsInfinity(newSpeed))
                {
                    currentSpeed = newSpeed;
                }
                resume.NextBlock = i + blocksToRead;
            }

            end = DateTime.Now;
            DicConsole.WriteLine();
            mhddLog.Close();
            ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024,
                         blockSize * (double)(blocks + 1) / 1024 / (totalDuration / 1000),
                         devicePath);
            dumpLog.WriteLine("Dump finished in {0} seconds.", (end - start).TotalSeconds);
            dumpLog.WriteLine("Average dump speed {0:F3} KiB/sec.",
                              (double)blockSize * (double)(blocks + 1) / 1024 / (totalDuration / 1000));
            dumpLog.WriteLine("Average write speed {0:F3} KiB/sec.",
                              (double)blockSize * (double)(blocks + 1) / 1024 / imageWriteDuration);

            #region Trimming
            if (resume.BadBlocks.Count > 0 && !aborted && !notrim && newTrim)
            {
                start = DateTime.UtcNow;
                dumpLog.WriteLine("Trimming bad sectors");

                ulong[] tmpArray = resume.BadBlocks.ToArray();
                foreach (ulong badSector in tmpArray)
                {
                    if (aborted)
                    {
                        currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                        dumpLog.WriteLine("Aborted!");
                        break;
                    }

                    DicConsole.Write("\rTrimming sector {0}", badSector);

                    error = dev.Read(out cmdBuf, out _, (uint)badSector, blockSize, 1, byteAddressed, TIMEOUT,
                                     out duration);

                    totalDuration += duration;

                    if (error)
                    {
                        continue;
                    }

                    resume.BadBlocks.Remove(badSector);
                    extents.Add(badSector);
                    outputPlugin.WriteSector(cmdBuf, badSector);
                }

                DicConsole.WriteLine();
                end = DateTime.UtcNow;
                dumpLog.WriteLine("Trimmming finished in {0} seconds.", (end - start).TotalSeconds);
            }
            #endregion Trimming

            #region Error handling
            if (resume.BadBlocks.Count > 0 && !aborted && retryPasses > 0)
            {
                int  pass              = 1;
                bool forward           = true;
                bool runningPersistent = false;

repeatRetryLba:
                ulong[] tmpArray = resume.BadBlocks.ToArray();
                foreach (ulong badSector in tmpArray)
                {
                    if (aborted)
                    {
                        currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                        dumpLog.WriteLine("Aborted!");
                        break;
                    }

                    DicConsole.Write("\rRetrying sector {0}, pass {1}, {3}{2}", badSector, pass,
                                     forward ? "forward" : "reverse",
                                     runningPersistent ? "recovering partial data, " : "");

                    error = dev.Read(out cmdBuf, out _, (uint)badSector, blockSize, 1, byteAddressed, TIMEOUT,
                                     out duration);

                    totalDuration += duration;

                    if (!error)
                    {
                        resume.BadBlocks.Remove(badSector);
                        extents.Add(badSector);
                        outputPlugin.WriteSector(cmdBuf, badSector);
                        dumpLog.WriteLine("Correctly retried block {0} in pass {1}.", badSector, pass);
                    }
                    else if (runningPersistent)
                    {
                        outputPlugin.WriteSector(cmdBuf, badSector);
                    }
                }

                if (pass < retryPasses && !aborted && resume.BadBlocks.Count > 0)
                {
                    pass++;
                    forward = !forward;
                    resume.BadBlocks.Sort();
                    resume.BadBlocks.Reverse();
                    goto repeatRetryLba;
                }

                DicConsole.WriteLine();
            }
            #endregion Error handling

            currentTry.Extents = ExtentsConverter.ToMetadata(extents);

            outputPlugin.SetDumpHardware(resume.Tries);
            if (preSidecar != null)
            {
                outputPlugin.SetCicmMetadata(preSidecar);
            }
            dumpLog.WriteLine("Closing output file.");
            DicConsole.WriteLine("Closing output file.");
            DateTime closeStart = DateTime.Now;
            outputPlugin.Close();
            DateTime closeEnd = DateTime.Now;
            dumpLog.WriteLine("Closed in {0} seconds.", (closeEnd - closeStart).TotalSeconds);

            if (aborted)
            {
                dumpLog.WriteLine("Aborted!");
                return;
            }

            double totalChkDuration = 0;
            if (!nometadata)
            {
                dumpLog.WriteLine("Creating sidecar.");
                FiltersList filters     = new FiltersList();
                IFilter     filter      = filters.GetFilter(outputPath);
                IMediaImage inputPlugin = ImageFormat.Detect(filter);
                if (!inputPlugin.Open(filter))
                {
                    throw new ArgumentException("Could not open created image.");
                }

                DateTime         chkStart = DateTime.UtcNow;
                CICMMetadataType sidecar  = Sidecar.Create(inputPlugin, outputPath, filter.Id, encoding);

                if (preSidecar != null)
                {
                    preSidecar.BlockMedia = sidecar.BlockMedia;
                    sidecar = preSidecar;
                }

                switch (dev.Type)
                {
                case DeviceType.MMC:
                    sidecar.BlockMedia[0].MultiMediaCard = new MultiMediaCardType();
                    break;

                case DeviceType.SecureDigital:
                    sidecar.BlockMedia[0].SecureDigital = new SecureDigitalType();
                    break;
                }

                DumpType cidDump = null;
                DumpType csdDump = null;
                DumpType ocrDump = null;

                if (cid != null)
                {
                    cidDump = new DumpType
                    {
                        Image     = outputPath,
                        Size      = cid.Length,
                        Checksums = Checksum.GetChecksums(cid).ToArray()
                    };

                    ret =
                        outputPlugin.WriteMediaTag(cid,
                                                   dev.Type == DeviceType.SecureDigital
                                                       ? MediaTagType.SD_CID
                                                       : MediaTagType.MMC_CID);

                    // Cannot write CID to image
                    if (!ret && !force)
                    {
                        dumpLog.WriteLine("Cannot write CID to output image.");
                        throw new ArgumentException(outputPlugin.ErrorMessage);
                    }
                }

                if (csd != null)
                {
                    csdDump = new DumpType
                    {
                        Image     = outputPath,
                        Size      = csd.Length,
                        Checksums = Checksum.GetChecksums(csd).ToArray()
                    };

                    ret =
                        outputPlugin.WriteMediaTag(csd,
                                                   dev.Type == DeviceType.SecureDigital
                                                       ? MediaTagType.SD_CSD
                                                       : MediaTagType.MMC_CSD);

                    // Cannot write CSD to image
                    if (!ret && !force)
                    {
                        dumpLog.WriteLine("Cannot write CSD to output image.");
                        throw new ArgumentException(outputPlugin.ErrorMessage);
                    }
                }

                if (ecsd != null)
                {
                    sidecar.BlockMedia[0].MultiMediaCard.ExtendedCSD = new DumpType
                    {
                        Image     = outputPath,
                        Size      = ecsd.Length,
                        Checksums = Checksum.GetChecksums(ecsd).ToArray()
                    };

                    ret = outputPlugin.WriteMediaTag(ecsd, MediaTagType.MMC_ExtendedCSD);

                    // Cannot write Extended CSD to image
                    if (!ret && !force)
                    {
                        dumpLog.WriteLine("Cannot write Extended CSD to output image.");
                        throw new ArgumentException(outputPlugin.ErrorMessage);
                    }
                }

                if (ocr != null)
                {
                    ocrDump = new DumpType
                    {
                        Image     = outputPath,
                        Size      = ocr.Length,
                        Checksums = Checksum.GetChecksums(ocr).ToArray()
                    };

                    ret =
                        outputPlugin.WriteMediaTag(ocr,
                                                   dev.Type == DeviceType.SecureDigital
                                                       ? MediaTagType.SD_OCR
                                                       : MediaTagType.MMC_OCR);

                    // Cannot write OCR to image
                    if (!ret && !force)
                    {
                        dumpLog.WriteLine("Cannot write OCR to output image.");
                        throw new ArgumentException(outputPlugin.ErrorMessage);
                    }
                }

                if (scr != null)
                {
                    sidecar.BlockMedia[0].SecureDigital.SCR = new DumpType
                    {
                        Image     = outputPath,
                        Size      = scr.Length,
                        Checksums = Checksum.GetChecksums(scr).ToArray()
                    };

                    ret = outputPlugin.WriteMediaTag(scr, MediaTagType.SD_SCR);

                    // Cannot write SCR to image
                    if (!ret && !force)
                    {
                        dumpLog.WriteLine("Cannot write SCR to output image.");
                        throw new ArgumentException(outputPlugin.ErrorMessage);
                    }
                }

                switch (dev.Type)
                {
                case DeviceType.MMC:
                    sidecar.BlockMedia[0].MultiMediaCard.CID = cidDump;
                    sidecar.BlockMedia[0].MultiMediaCard.CSD = csdDump;
                    sidecar.BlockMedia[0].MultiMediaCard.OCR = ocrDump;
                    break;

                case DeviceType.SecureDigital:
                    sidecar.BlockMedia[0].SecureDigital.CID = cidDump;
                    sidecar.BlockMedia[0].SecureDigital.CSD = csdDump;
                    sidecar.BlockMedia[0].SecureDigital.OCR = ocrDump;
                    break;
                }

                end = DateTime.UtcNow;

                totalChkDuration = (end - chkStart).TotalMilliseconds;
                dumpLog.WriteLine("Sidecar created in {0} seconds.", (end - chkStart).TotalSeconds);
                dumpLog.WriteLine("Average checksum speed {0:F3} KiB/sec.",
                                  (double)blockSize * (double)(blocks + 1) / 1024 / (totalChkDuration / 1000));

                string xmlDskTyp = null, xmlDskSubTyp = null;
                switch (dev.Type)
                {
                case DeviceType.MMC:
                    Metadata.MediaType.MediaTypeToString(MediaType.MMC, out xmlDskTyp, out xmlDskSubTyp);
                    sidecar.BlockMedia[0].Dimensions = Dimensions.DimensionsFromMediaType(MediaType.MMC);
                    break;

                case DeviceType.SecureDigital:
                    Metadata.MediaType.MediaTypeToString(MediaType.SecureDigital, out xmlDskTyp, out xmlDskSubTyp);
                    sidecar.BlockMedia[0].Dimensions = Dimensions.DimensionsFromMediaType(MediaType.SecureDigital);
                    break;
                }

                sidecar.BlockMedia[0].DiskType    = xmlDskTyp;
                sidecar.BlockMedia[0].DiskSubType = xmlDskSubTyp;
                // TODO: Implement device firmware revision
                sidecar.BlockMedia[0].LogicalBlocks     = (long)blocks;
                sidecar.BlockMedia[0].PhysicalBlockSize = physicalBlockSize > 0 ? physicalBlockSize : (int)blockSize;
                sidecar.BlockMedia[0].LogicalBlockSize  = (int)blockSize;
                sidecar.BlockMedia[0].Manufacturer      = dev.Manufacturer;
                sidecar.BlockMedia[0].Model             = dev.Model;
                sidecar.BlockMedia[0].Serial            = dev.Serial;
                sidecar.BlockMedia[0].Size = (long)(blocks * blockSize);

                DicConsole.WriteLine("Writing metadata sidecar");

                FileStream xmlFs = new FileStream(outputPrefix + ".cicm.xml", FileMode.Create);

                XmlSerializer xmlSer = new XmlSerializer(typeof(CICMMetadataType));
                xmlSer.Serialize(xmlFs, sidecar);
                xmlFs.Close();
            }

            DicConsole.WriteLine();

            DicConsole.WriteLine("Took a total of {0:F3} seconds ({1:F3} processing commands, {2:F3} checksumming, {3:F3} writing, {4:F3} closing).",
                                 (end - start).TotalSeconds, totalDuration / 1000,
                                 totalChkDuration / 1000,
                                 imageWriteDuration, (closeEnd - closeStart).TotalSeconds);
            DicConsole.WriteLine("Avegare speed: {0:F3} MiB/sec.",
                                 (double)blockSize * (double)(blocks + 1) / 1048576 / (totalDuration / 1000));
            DicConsole.WriteLine("Fastest speed burst: {0:F3} MiB/sec.", maxSpeed);
            DicConsole.WriteLine("Slowest speed burst: {0:F3} MiB/sec.", minSpeed);
            DicConsole.WriteLine("{0} sectors could not be read.", resume.BadBlocks.Count);
            if (resume.BadBlocks.Count > 0)
            {
                resume.BadBlocks.Sort();
            }
            DicConsole.WriteLine();

            switch (dev.Type)
            {
            case DeviceType.MMC:
                Statistics.AddMedia(MediaType.MMC, true);
                break;

            case DeviceType.SecureDigital:
                Statistics.AddMedia(MediaType.SecureDigital, true);
                break;
            }
        }
示例#36
0
 public WithDimensions()
 {
     _value = new Dimensions().WithHeight(448);
 }
示例#37
0
 public ComputerDetail()
 {
     Dimensions = new Dimensions();
 }
示例#38
0
 public static Dimensions ResizeToTargetAspectRatio(Dimensions originalDimensions, Dimensions targetDimensions)
 {
     return(originalDimensions.AspectRatio > targetDimensions.AspectRatio
                         ? ResizeHeightMaintainAspectRatio(originalDimensions, targetDimensions.Height)
                         : ResizeWidthMaintainAspectRatio(originalDimensions, targetDimensions.Width));
 }
示例#39
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        /// <param name="landscapeDimensions">
        /// The dimensions of the landscape.
        /// </param>
        protected Collection(Dimensions landscapeDimensions)
        {
            this.landscapeDimensions = landscapeDimensions;
        }
示例#40
0
        /// <summary>
        /// Applies a layout animation for the given view on the transition to
        /// the given coordinates and dimensions.
        /// </summary>
        /// <param name="viewManager">The view manager for the native view.</param>
        /// <param name="view">The native view to animate.</param>
        /// <param name="dimensions">The new view dimensions to animate to.</param>
        public void ApplyLayoutUpdate(IViewManager viewManager, FrameworkElement view, Dimensions dimensions)
        {
            DispatcherHelpers.AssertOnDispatcher();

            var currentDimensions = viewManager.GetDimensions(view);
            var layoutAnimation   = IsZeroOrNaN(currentDimensions.Width) || IsZeroOrNaN(currentDimensions.Height)
                ? _layoutCreateAnimation
                : _layoutUpdateAnimation;

            var animation = layoutAnimation.CreateAnimation(viewManager, view, dimensions);

            if (animation == null)
            {
                viewManager.SetDimensions(view, dimensions);
            }
            else
            {
                StartAnimation(view, animation);
            }
        }
 /// <summary>
 /// Sets the dimensions of the view.
 /// </summary>
 /// <param name="view">The view.</param>
 /// <param name="dimensions">The output buffer.</param>
 public override void SetDimensions(Border view, Dimensions dimensions)
 {
     base.SetDimensions(view, dimensions);
     SetUriFromMultipleSources(view);
 }
 public override void SetDimensions(Line view, Dimensions dimensions)
 {
 }
 /// <summary>
 /// Sets the dimensions of the view.
 /// </summary>
 /// <param name="view">The view.</param>
 /// <param name="dimensions">The output buffer.</param>
 public override void SetDimensions(PasswordBox view, Dimensions dimensions)
 {
     base.SetDimensions(view, dimensions);
     view.MinWidth  = dimensions.Width;
     view.MinHeight = dimensions.Height;
 }
示例#44
0
        public void ChangePrice_SamePriceAsBefore_ExceptionThrown()
        {
            // arrange
            var provider          = Provider.MakeProvider("Julio", "09883060000174");
            var providerOrder     = ProviderOrder.MakeProviderOrder(7, provider);
            var product           = Product.MakeProduct("Test product", "Test product", 15, Dimensions.MakeDimensions(11, 12, 13));
            var providerOrderItem = ProviderOrderItem.MakeProviderOrderItem(providerOrder, product, 5);

            // act
            Assert.Throws <ArgumentException>(() => providerOrderItem.ChangePrice(15));
        }
示例#45
0
 public void Init()
 {
     Dimensions.Subscribe(dim => ColoredFrame = new byte[dim.Width * dim.Height * 3]);
 }
示例#46
0
 /// <summary>
 /// Returns True iff `self` is fully defined in every dimension.
 /// </summary>
 /// <returns></returns>
 public bool is_fully_defined()
 {
     return(Dimensions != null && Dimensions.Count(x => x < 1) == 0);
 }
示例#47
0
 public override void SetDimensions(Ellipse view, Dimensions dimensions)
 {
 }
示例#48
0
 /// <inheritdoc />
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         if (Type != null)
         {
             hashCode = hashCode * 59 + Type.GetHashCode();
         }
         if (Visible != null)
         {
             hashCode = hashCode * 59 + Visible.GetHashCode();
         }
         if (Name != null)
         {
             hashCode = hashCode * 59 + Name.GetHashCode();
         }
         if (UId != null)
         {
             hashCode = hashCode * 59 + UId.GetHashCode();
         }
         if (Meta != null)
         {
             hashCode = hashCode * 59 + Meta.GetHashCode();
         }
         if (MetaArray != null)
         {
             hashCode = hashCode * 59 + MetaArray.GetHashCode();
         }
         if (Stream != null)
         {
             hashCode = hashCode * 59 + Stream.GetHashCode();
         }
         if (Transforms != null)
         {
             hashCode = hashCode * 59 + Transforms.GetHashCode();
         }
         if (UiRevision != null)
         {
             hashCode = hashCode * 59 + UiRevision.GetHashCode();
         }
         if (Domain != null)
         {
             hashCode = hashCode * 59 + Domain.GetHashCode();
         }
         if (HoverInfo != null)
         {
             hashCode = hashCode * 59 + HoverInfo.GetHashCode();
         }
         if (HoverOn != null)
         {
             hashCode = hashCode * 59 + HoverOn.GetHashCode();
         }
         if (HoverTemplate != null)
         {
             hashCode = hashCode * 59 + HoverTemplate.GetHashCode();
         }
         if (Arrangement != null)
         {
             hashCode = hashCode * 59 + Arrangement.GetHashCode();
         }
         if (BundleColors != null)
         {
             hashCode = hashCode * 59 + BundleColors.GetHashCode();
         }
         if (SortPaths != null)
         {
             hashCode = hashCode * 59 + SortPaths.GetHashCode();
         }
         if (LabelFont != null)
         {
             hashCode = hashCode * 59 + LabelFont.GetHashCode();
         }
         if (TickFont != null)
         {
             hashCode = hashCode * 59 + TickFont.GetHashCode();
         }
         if (Dimensions != null)
         {
             hashCode = hashCode * 59 + Dimensions.GetHashCode();
         }
         if (Line != null)
         {
             hashCode = hashCode * 59 + Line.GetHashCode();
         }
         if (Counts != null)
         {
             hashCode = hashCode * 59 + Counts.GetHashCode();
         }
         if (CountsArray != null)
         {
             hashCode = hashCode * 59 + CountsArray.GetHashCode();
         }
         if (MetaSrc != null)
         {
             hashCode = hashCode * 59 + MetaSrc.GetHashCode();
         }
         if (CountsSrc != null)
         {
             hashCode = hashCode * 59 + CountsSrc.GetHashCode();
         }
         return(hashCode);
     }
 }
示例#49
0
 /// <summary>
 /// Sets the dimensions of the view.
 /// </summary>
 /// <param name="view">The view.</param>
 /// <param name="dimensions">The output buffer.</param>
 /// <remarks>
 /// This is a no-op as all layout is performed by the parent text block.
 /// </remarks>
 public override void SetDimensions(Span view, Dimensions dimensions)
 {
 }
示例#50
0
 private void WorldPanel_SizeChanged(object sender, System.EventArgs e)
 {
     Dimensions.SetScreenSize(this.Size);
 }
示例#51
0
        public void ChangeAmount_ZeroAmount_ExceptionThrown()
        {
            // arrange
            var provider      = Provider.MakeProvider("Julio", "09883060000174");
            var providerOrder = ProviderOrder.MakeProviderOrder(7, provider);
            var product       = Product.MakeProduct("Test product", "Test product", 15, Dimensions.MakeDimensions(11, 12, 13));

            product.UpdateAmount(15);
            var providerOrderItem = ProviderOrderItem.MakeProviderOrderItem(providerOrder, product, 5);

            // act
            Assert.Throws <ArgumentException>(() => providerOrderItem.ChangeAmount(0));
        }
示例#52
0
        /// <summary>
        /// Create highlighter window
        /// </summary>
        public void InitializeWindow()
        {
            canvas = new Canvas();
            var vb = new Viewbox()
            {
                Child = canvas
            };

            this.HighlightWindow = new Window()
            {
                Content   = vb,
                Title     = Properties.Resources.ScreenshotWindowTitle,
                Icon      = Application.Current.MainWindow.Icon,
                MinHeight = 80
            };

            bdClick = new Border()
            {
                Child = new TextBlock()
                {
                    FontSize            = 28,
                    Text                = Properties.Resources.ScreenshotWindowTitle,
                    Background          = new SolidColorBrush(Colors.White),
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment   = VerticalAlignment.Center,
                },
                Width               = 620,
                Height              = 70,
                Visibility          = Visibility.Collapsed,
                BorderBrush         = System.Windows.Media.Brushes.Red,
                BorderThickness     = new Thickness(5),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment   = VerticalAlignment.Center,
            };

            this.HighlightWindow.Closing    += onClosing;
            this.HighlightWindow.Closed     += onClosed;
            this.HighlightWindow.MouseDown  += onClick;
            this.HighlightWindow.MouseEnter += onClick;

            canvas.Width  = Dimensions.Width;
            canvas.Height = Dimensions.Height;
            canvas.Children.Add(bdClick);
            bdClick.SetValue(Canvas.LeftProperty, (canvas.Width - bdClick.Width) / 2);
            bdClick.SetValue(Canvas.TopProperty, (canvas.Height - bdClick.Height) / 2);
            canvas.Background = ib;

            if (WinRect.IsEmpty)
            {
                var xyDpi = Axe.Windows.Desktop.Utility.ExtensionMethods.GetWPFWindowPositioningDPI();
                this.HighlightWindow.Top  = Dimensions.Top / xyDpi;
                this.HighlightWindow.Left = Dimensions.Left / xyDpi;

                var dpi = Dimensions.GetDPI();
                this.HighlightWindow.Width  = Dimensions.Width / dpi;
                this.HighlightWindow.Height = Dimensions.Height / dpi;
            }
            else
            {
                this.HighlightWindow.Top    = WinRect.Top;
                this.HighlightWindow.Left   = WinRect.Left;
                this.HighlightWindow.Width  = WinRect.Width;
                this.HighlightWindow.Height = WinRect.Height;
            }

            HighlightWindow.Show();
        }
示例#53
0
        public override int GetHashCode()
        {
            unchecked // Overflow is fine, just wrap
            {
                int hashCode = 41;

                if (Type != null)
                {
                    hashCode = hashCode * 59 + Type.GetHashCode();
                }

                if (Visible != null)
                {
                    hashCode = hashCode * 59 + Visible.GetHashCode();
                }

                if (ShowLegend != null)
                {
                    hashCode = hashCode * 59 + ShowLegend.GetHashCode();
                }

                if (LegendGroup != null)
                {
                    hashCode = hashCode * 59 + LegendGroup.GetHashCode();
                }

                if (Name != null)
                {
                    hashCode = hashCode * 59 + Name.GetHashCode();
                }

                if (UId != null)
                {
                    hashCode = hashCode * 59 + UId.GetHashCode();
                }

                if (Ids != null)
                {
                    hashCode = hashCode * 59 + Ids.GetHashCode();
                }

                if (CustomData != null)
                {
                    hashCode = hashCode * 59 + CustomData.GetHashCode();
                }

                if (Meta != null)
                {
                    hashCode = hashCode * 59 + Meta.GetHashCode();
                }

                if (MetaArray != null)
                {
                    hashCode = hashCode * 59 + MetaArray.GetHashCode();
                }

                if (SelectedPoints != null)
                {
                    hashCode = hashCode * 59 + SelectedPoints.GetHashCode();
                }

                if (HoverInfo != null)
                {
                    hashCode = hashCode * 59 + HoverInfo.GetHashCode();
                }

                if (HoverInfoArray != null)
                {
                    hashCode = hashCode * 59 + HoverInfoArray.GetHashCode();
                }

                if (HoverLabel != null)
                {
                    hashCode = hashCode * 59 + HoverLabel.GetHashCode();
                }

                if (Stream != null)
                {
                    hashCode = hashCode * 59 + Stream.GetHashCode();
                }

                if (Transforms != null)
                {
                    hashCode = hashCode * 59 + Transforms.GetHashCode();
                }

                if (UiRevision != null)
                {
                    hashCode = hashCode * 59 + UiRevision.GetHashCode();
                }

                if (Dimensions != null)
                {
                    hashCode = hashCode * 59 + Dimensions.GetHashCode();
                }

                if (Text != null)
                {
                    hashCode = hashCode * 59 + Text.GetHashCode();
                }

                if (TextArray != null)
                {
                    hashCode = hashCode * 59 + TextArray.GetHashCode();
                }

                if (HoverText != null)
                {
                    hashCode = hashCode * 59 + HoverText.GetHashCode();
                }

                if (HoverTextArray != null)
                {
                    hashCode = hashCode * 59 + HoverTextArray.GetHashCode();
                }

                if (HoverTemplate != null)
                {
                    hashCode = hashCode * 59 + HoverTemplate.GetHashCode();
                }

                if (HoverTemplateArray != null)
                {
                    hashCode = hashCode * 59 + HoverTemplateArray.GetHashCode();
                }

                if (Marker != null)
                {
                    hashCode = hashCode * 59 + Marker.GetHashCode();
                }

                if (XAxes != null)
                {
                    hashCode = hashCode * 59 + XAxes.GetHashCode();
                }

                if (YAxes != null)
                {
                    hashCode = hashCode * 59 + YAxes.GetHashCode();
                }

                if (Diagonal != null)
                {
                    hashCode = hashCode * 59 + Diagonal.GetHashCode();
                }

                if (ShowUpperHalf != null)
                {
                    hashCode = hashCode * 59 + ShowUpperHalf.GetHashCode();
                }

                if (ShowLowerHalf != null)
                {
                    hashCode = hashCode * 59 + ShowLowerHalf.GetHashCode();
                }

                if (Selected != null)
                {
                    hashCode = hashCode * 59 + Selected.GetHashCode();
                }

                if (Unselected != null)
                {
                    hashCode = hashCode * 59 + Unselected.GetHashCode();
                }

                if (Opacity != null)
                {
                    hashCode = hashCode * 59 + Opacity.GetHashCode();
                }

                if (IdsSrc != null)
                {
                    hashCode = hashCode * 59 + IdsSrc.GetHashCode();
                }

                if (CustomDataSrc != null)
                {
                    hashCode = hashCode * 59 + CustomDataSrc.GetHashCode();
                }

                if (MetaSrc != null)
                {
                    hashCode = hashCode * 59 + MetaSrc.GetHashCode();
                }

                if (HoverInfoSrc != null)
                {
                    hashCode = hashCode * 59 + HoverInfoSrc.GetHashCode();
                }

                if (TextSrc != null)
                {
                    hashCode = hashCode * 59 + TextSrc.GetHashCode();
                }

                if (HoverTextSrc != null)
                {
                    hashCode = hashCode * 59 + HoverTextSrc.GetHashCode();
                }

                if (HoverTemplateSrc != null)
                {
                    hashCode = hashCode * 59 + HoverTemplateSrc.GetHashCode();
                }

                return(hashCode);
            }
        }
示例#54
0
        public void MakeItem_ValidParameters_ItemCreated()
        {
            // arrange
            var provider      = Provider.MakeProvider("Julio", "09883060000174");
            var providerOrder = ProviderOrder.MakeProviderOrder(7, provider);
            var product       = Product.MakeProduct("Test product", "Test product", 15, Dimensions.MakeDimensions(11, 12, 13));

            // act
            var providerOrderItem = ProviderOrderItem.MakeProviderOrderItem(providerOrder, product, 5);

            // assert
            Assert.Equal(providerOrderItem.Amount, 5);
            Assert.Equal(providerOrderItem.Deposits.Count, 1);
            Assert.Equal(providerOrderItem.Price, 15);
            Assert.Equal(providerOrderItem.ProductId, product.Id);
            Assert.Equal(providerOrderItem.ProviderOrderId, providerOrder.Id);
            Assert.Equal(providerOrderItem.TotalValue, 75);
            Assert.Equal(providerOrder.TotalValue, 75);
            Assert.Equal(product.Amount, 5);
        }
 public void SetDimensions(DependencyObject view, Dimensions dimensions)
 {
     throw new NotImplementedException();
 }
示例#56
0
        /// <inheritdoc />
        public bool Equals([AllowNull] ParCats other)
        {
            if (other == null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Type == other.Type ||
                     Type != null &&
                     Type.Equals(other.Type)
                     ) &&
                 (
                     Visible == other.Visible ||
                     Visible != null &&
                     Visible.Equals(other.Visible)
                 ) &&
                 (
                     Name == other.Name ||
                     Name != null &&
                     Name.Equals(other.Name)
                 ) &&
                 (
                     UId == other.UId ||
                     UId != null &&
                     UId.Equals(other.UId)
                 ) &&
                 (
                     Meta == other.Meta ||
                     Meta != null &&
                     Meta.Equals(other.Meta)
                 ) &&
                 (
                     Equals(MetaArray, other.MetaArray) ||
                     MetaArray != null && other.MetaArray != null &&
                     MetaArray.SequenceEqual(other.MetaArray)
                 ) &&
                 (
                     Stream == other.Stream ||
                     Stream != null &&
                     Stream.Equals(other.Stream)
                 ) &&
                 (
                     Equals(Transforms, other.Transforms) ||
                     Transforms != null && other.Transforms != null &&
                     Transforms.SequenceEqual(other.Transforms)
                 ) &&
                 (
                     UiRevision == other.UiRevision ||
                     UiRevision != null &&
                     UiRevision.Equals(other.UiRevision)
                 ) &&
                 (
                     Domain == other.Domain ||
                     Domain != null &&
                     Domain.Equals(other.Domain)
                 ) &&
                 (
                     HoverInfo == other.HoverInfo ||
                     HoverInfo != null &&
                     HoverInfo.Equals(other.HoverInfo)
                 ) &&
                 (
                     HoverOn == other.HoverOn ||
                     HoverOn != null &&
                     HoverOn.Equals(other.HoverOn)
                 ) &&
                 (
                     HoverTemplate == other.HoverTemplate ||
                     HoverTemplate != null &&
                     HoverTemplate.Equals(other.HoverTemplate)
                 ) &&
                 (
                     Arrangement == other.Arrangement ||
                     Arrangement != null &&
                     Arrangement.Equals(other.Arrangement)
                 ) &&
                 (
                     BundleColors == other.BundleColors ||
                     BundleColors != null &&
                     BundleColors.Equals(other.BundleColors)
                 ) &&
                 (
                     SortPaths == other.SortPaths ||
                     SortPaths != null &&
                     SortPaths.Equals(other.SortPaths)
                 ) &&
                 (
                     LabelFont == other.LabelFont ||
                     LabelFont != null &&
                     LabelFont.Equals(other.LabelFont)
                 ) &&
                 (
                     TickFont == other.TickFont ||
                     TickFont != null &&
                     TickFont.Equals(other.TickFont)
                 ) &&
                 (
                     Equals(Dimensions, other.Dimensions) ||
                     Dimensions != null && other.Dimensions != null &&
                     Dimensions.SequenceEqual(other.Dimensions)
                 ) &&
                 (
                     Line == other.Line ||
                     Line != null &&
                     Line.Equals(other.Line)
                 ) &&
                 (
                     Counts == other.Counts ||
                     Counts != null &&
                     Counts.Equals(other.Counts)
                 ) &&
                 (
                     Equals(CountsArray, other.CountsArray) ||
                     CountsArray != null && other.CountsArray != null &&
                     CountsArray.SequenceEqual(other.CountsArray)
                 ) &&
                 (
                     MetaSrc == other.MetaSrc ||
                     MetaSrc != null &&
                     MetaSrc.Equals(other.MetaSrc)
                 ) &&
                 (
                     CountsSrc == other.CountsSrc ||
                     CountsSrc != null &&
                     CountsSrc.Equals(other.CountsSrc)
                 ));
        }
 public void OnResize(Dimensions dimensions)
 {
     (Node as ContentSizedNodeBase).GetSize((dimensions.Width, dimensions.Height));
 }
示例#58
0
        public bool Equals([AllowNull] Splom other)
        {
            if (other == null)
            {
                return(false);
            }

            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return((Type == other.Type && Type != null && other.Type != null && Type.Equals(other.Type)) &&
                   (Visible == other.Visible && Visible != null && other.Visible != null && Visible.Equals(other.Visible)) &&
                   (ShowLegend == other.ShowLegend && ShowLegend != null && other.ShowLegend != null && ShowLegend.Equals(other.ShowLegend)) &&
                   (LegendGroup == other.LegendGroup && LegendGroup != null && other.LegendGroup != null && LegendGroup.Equals(other.LegendGroup)) &&
                   (Name == other.Name && Name != null && other.Name != null && Name.Equals(other.Name)) &&
                   (UId == other.UId && UId != null && other.UId != null && UId.Equals(other.UId)) &&
                   (Equals(Ids, other.Ids) || Ids != null && other.Ids != null && Ids.SequenceEqual(other.Ids)) &&
                   (Equals(CustomData, other.CustomData) || CustomData != null && other.CustomData != null && CustomData.SequenceEqual(other.CustomData)) &&
                   (Meta == other.Meta && Meta != null && other.Meta != null && Meta.Equals(other.Meta)) &&
                   (Equals(MetaArray, other.MetaArray) || MetaArray != null && other.MetaArray != null && MetaArray.SequenceEqual(other.MetaArray)) &&
                   (SelectedPoints == other.SelectedPoints && SelectedPoints != null && other.SelectedPoints != null && SelectedPoints.Equals(other.SelectedPoints)) &&
                   (HoverInfo == other.HoverInfo && HoverInfo != null && other.HoverInfo != null && HoverInfo.Equals(other.HoverInfo)) &&
                   (Equals(HoverInfoArray, other.HoverInfoArray) || HoverInfoArray != null && other.HoverInfoArray != null && HoverInfoArray.SequenceEqual(other.HoverInfoArray)) &&
                   (HoverLabel == other.HoverLabel && HoverLabel != null && other.HoverLabel != null && HoverLabel.Equals(other.HoverLabel)) &&
                   (Stream == other.Stream && Stream != null && other.Stream != null && Stream.Equals(other.Stream)) &&
                   (Equals(Transforms, other.Transforms) || Transforms != null && other.Transforms != null && Transforms.SequenceEqual(other.Transforms)) &&
                   (UiRevision == other.UiRevision && UiRevision != null && other.UiRevision != null && UiRevision.Equals(other.UiRevision)) &&
                   (Equals(Dimensions, other.Dimensions) || Dimensions != null && other.Dimensions != null && Dimensions.SequenceEqual(other.Dimensions)) &&
                   (Text == other.Text && Text != null && other.Text != null && Text.Equals(other.Text)) &&
                   (Equals(TextArray, other.TextArray) || TextArray != null && other.TextArray != null && TextArray.SequenceEqual(other.TextArray)) &&
                   (HoverText == other.HoverText && HoverText != null && other.HoverText != null && HoverText.Equals(other.HoverText)) &&
                   (Equals(HoverTextArray, other.HoverTextArray) || HoverTextArray != null && other.HoverTextArray != null && HoverTextArray.SequenceEqual(other.HoverTextArray)) &&
                   (HoverTemplate == other.HoverTemplate && HoverTemplate != null && other.HoverTemplate != null && HoverTemplate.Equals(other.HoverTemplate)) &&
                   (Equals(HoverTemplateArray, other.HoverTemplateArray) ||
                    HoverTemplateArray != null && other.HoverTemplateArray != null && HoverTemplateArray.SequenceEqual(other.HoverTemplateArray)) &&
                   (Marker == other.Marker && Marker != null && other.Marker != null && Marker.Equals(other.Marker)) &&
                   (Equals(XAxes, other.XAxes) || XAxes != null && other.XAxes != null && XAxes.SequenceEqual(other.XAxes)) &&
                   (Equals(YAxes, other.YAxes) || YAxes != null && other.YAxes != null && YAxes.SequenceEqual(other.YAxes)) &&
                   (Diagonal == other.Diagonal && Diagonal != null && other.Diagonal != null && Diagonal.Equals(other.Diagonal)) &&
                   (ShowUpperHalf == other.ShowUpperHalf && ShowUpperHalf != null && other.ShowUpperHalf != null && ShowUpperHalf.Equals(other.ShowUpperHalf)) &&
                   (ShowLowerHalf == other.ShowLowerHalf && ShowLowerHalf != null && other.ShowLowerHalf != null && ShowLowerHalf.Equals(other.ShowLowerHalf)) &&
                   (Selected == other.Selected && Selected != null && other.Selected != null && Selected.Equals(other.Selected)) &&
                   (Unselected == other.Unselected && Unselected != null && other.Unselected != null && Unselected.Equals(other.Unselected)) &&
                   (Opacity == other.Opacity && Opacity != null && other.Opacity != null && Opacity.Equals(other.Opacity)) &&
                   (IdsSrc == other.IdsSrc && IdsSrc != null && other.IdsSrc != null && IdsSrc.Equals(other.IdsSrc)) &&
                   (CustomDataSrc == other.CustomDataSrc && CustomDataSrc != null && other.CustomDataSrc != null && CustomDataSrc.Equals(other.CustomDataSrc)) &&
                   (MetaSrc == other.MetaSrc && MetaSrc != null && other.MetaSrc != null && MetaSrc.Equals(other.MetaSrc)) &&
                   (HoverInfoSrc == other.HoverInfoSrc && HoverInfoSrc != null && other.HoverInfoSrc != null && HoverInfoSrc.Equals(other.HoverInfoSrc)) &&
                   (TextSrc == other.TextSrc && TextSrc != null && other.TextSrc != null && TextSrc.Equals(other.TextSrc)) &&
                   (HoverTextSrc == other.HoverTextSrc && HoverTextSrc != null && other.HoverTextSrc != null && HoverTextSrc.Equals(other.HoverTextSrc)) &&
                   (HoverTemplateSrc == other.HoverTemplateSrc && HoverTemplateSrc != null && other.HoverTemplateSrc != null && HoverTemplateSrc.Equals(other.HoverTemplateSrc)));
        }
示例#59
0
        protected override void DrawSelf(SpriteBatch spriteBatch)
        {
            spriteBatch.DrawSlot(Dimensions, Color.White, backgroundTexture);

            float scale = Math.Min(Dimensions.Width / backgroundTexture.Width, Dimensions.Height / backgroundTexture.Height);

            if (!Item.IsAir)
            {
                Texture2D itemTexture = Main.itemTexture[Item.type];
                Rectangle rect        = Main.itemAnimations[Item.type] != null ? Main.itemAnimations[Item.type].GetFrame(itemTexture) : itemTexture.Frame();
                Color     newColor    = Color.White;
                float     pulseScale  = 1f;
                ItemSlot.GetItemLight(ref newColor, ref pulseScale, Item);
                int   height    = rect.Height;
                int   width     = rect.Width;
                float drawScale = 1f;

                float availableWidth = InnerDimensions.Width;
                if (width > availableWidth || height > availableWidth)
                {
                    if (width > height)
                    {
                        drawScale = availableWidth / width;
                    }
                    else
                    {
                        drawScale = availableWidth / height;
                    }
                }

                drawScale *= scale;
                Vector2 vector    = backgroundTexture.Size() * scale;
                Vector2 position2 = Dimensions.Position() + vector / 2f - rect.Size() * drawScale / 2f;
                Vector2 origin    = rect.Size() * (pulseScale / 2f - 0.5f);

                if (ItemLoader.PreDrawInInventory(Item, spriteBatch, position2, rect, Item.GetAlpha(newColor), Item.GetColor(Color.White), origin, drawScale * pulseScale))
                {
                    spriteBatch.Draw(itemTexture, position2, rect, Item.GetAlpha(newColor), 0f, origin, drawScale * pulseScale, SpriteEffects.None, 0f);
                    if (Item.color != Color.Transparent)
                    {
                        spriteBatch.Draw(itemTexture, position2, rect, Item.GetColor(Color.White), 0f, origin, drawScale * pulseScale, SpriteEffects.None, 0f);
                    }
                }

                ItemLoader.PostDrawInInventory(Item, spriteBatch, position2, rect, Item.GetAlpha(newColor), Item.GetColor(Color.White), origin, drawScale * pulseScale);
                if (ItemID.Sets.TrapSigned[Item.type])
                {
                    spriteBatch.Draw(Main.wireTexture, Dimensions.Position() + new Vector2(40f, 40f) * scale, new Rectangle(4, 58, 8, 8), Color.White, 0f, new Vector2(4f), 1f, SpriteEffects.None, 0f);
                }
                if (Stack > 1)
                {
                    ChatManager.DrawColorCodedStringWithShadow(spriteBatch, Main.fontItemStack, Stack < 1000 ? Stack.ToString() : Stack.ToSI("N0"), Dimensions.Position() + new Vector2(10f, 26f) * scale, Color.White, 0f, Vector2.Zero, new Vector2(scale), -1f, scale);
                }

                if (IsMouseHovering)
                {
                    Main.LocalPlayer.showItemIcon = false;
                    Main.ItemIconCacheUpdate(0);
                    Main.HoverItem       = Item.Clone();
                    Main.HoverItem.stack = Stack;
                    Main.hoverItemName   = Main.HoverItem.Name;

                    if (ItemSlot.ShiftInUse)
                    {
                        Hooking.SetCursor("Terraria/UI/Cursor_7");
                    }
                }
            }
        }
示例#60
0
        /// <summary>Dumps a MultiMediaCard or SecureDigital flash card</summary>
        void SecureDigital()
        {
            if (_dumpRaw)
            {
                if (_force)
                {
                    ErrorMessage?.
                    Invoke("Raw dumping is not supported in MultiMediaCard or SecureDigital devices. Continuing...");
                }
                else
                {
                    StoppingErrorMessage?.
                    Invoke("Raw dumping is not supported in MultiMediaCard or SecureDigital devices. Aborting...");

                    return;
                }
            }

            bool         sense;
            const ushort sdProfile = 0x0001;
            const uint   timeout   = 5;
            double       duration;
            ushort       blocksToRead = 128;
            uint         blockSize    = 512;
            ulong        blocks       = 0;

            byte[] csd  = null;
            byte[] ocr  = null;
            byte[] ecsd = null;
            byte[] scr  = null;
            uint   physicalBlockSize = 0;
            bool   byteAddressed     = true;

            uint[] response;
            bool   supportsCmd23 = false;

            Dictionary <MediaTagType, byte[]> mediaTags = new Dictionary <MediaTagType, byte[]>();

            switch (_dev.Type)
            {
            case DeviceType.MMC:
            {
                UpdateStatus?.Invoke("Reading CSD");
                _dumpLog.WriteLine("Reading CSD");
                sense = _dev.ReadCsd(out csd, out response, timeout, out duration);

                if (!sense)
                {
                    CSD csdDecoded = Decoders.MMC.Decoders.DecodeCSD(csd);
                    blocks    = (ulong)((csdDecoded.Size + 1) * Math.Pow(2, csdDecoded.SizeMultiplier + 2));
                    blockSize = (uint)Math.Pow(2, csdDecoded.ReadBlockLength);

                    mediaTags.Add(MediaTagType.MMC_CSD, null);

                    // Found at least since MMC System Specification 3.31
                    supportsCmd23 = csdDecoded.Version >= 3;

                    if (csdDecoded.Size == 0xFFF)
                    {
                        UpdateStatus?.Invoke("Reading Extended CSD");
                        _dumpLog.WriteLine("Reading Extended CSD");
                        sense = _dev.ReadExtendedCsd(out ecsd, out response, timeout, out duration);

                        if (!sense)
                        {
                            ExtendedCSD ecsdDecoded = Decoders.MMC.Decoders.DecodeExtendedCSD(ecsd);
                            blocks    = ecsdDecoded.SectorCount;
                            blockSize = (uint)(ecsdDecoded.SectorSize == 1 ? 4096 : 512);

                            if (ecsdDecoded.NativeSectorSize == 0)
                            {
                                physicalBlockSize = 512;
                            }
                            else if (ecsdDecoded.NativeSectorSize == 1)
                            {
                                physicalBlockSize = 4096;
                            }

                            blocksToRead = (ushort)(ecsdDecoded.OptimalReadSize * 4096 / blockSize);

                            if (blocksToRead == 0)
                            {
                                blocksToRead = 128;
                            }

                            // Supposing it's high-capacity MMC if it has Extended CSD...
                            byteAddressed = false;
                            mediaTags.Add(MediaTagType.MMC_ExtendedCSD, null);
                        }
                        else
                        {
                            _errorLog?.WriteLine("Read eCSD", _dev.Error, _dev.LastError, response);
                            ecsd = null;
                        }
                    }
                }
                else
                {
                    _errorLog?.WriteLine("Read CSD", _dev.Error, _dev.LastError, response);
                    csd = null;
                }

                UpdateStatus?.Invoke("Reading OCR");
                _dumpLog.WriteLine("Reading OCR");
                sense = _dev.ReadOcr(out ocr, out response, timeout, out duration);

                if (sense)
                {
                    _errorLog?.WriteLine("Read OCR", _dev.Error, _dev.LastError, response);
                    ocr = null;
                }
                else
                {
                    mediaTags.Add(MediaTagType.MMC_OCR, null);
                }

                break;
            }

            case DeviceType.SecureDigital:
            {
                UpdateStatus?.Invoke("Reading CSD");
                _dumpLog.WriteLine("Reading CSD");
                sense = _dev.ReadCsd(out csd, out response, timeout, out duration);

                if (!sense)
                {
                    Decoders.SecureDigital.CSD csdDecoded = Decoders.SecureDigital.Decoders.DecodeCSD(csd);

                    blocks = (ulong)(csdDecoded.Structure == 0
                                             ? (csdDecoded.Size + 1) * Math.Pow(2, csdDecoded.SizeMultiplier + 2)
                                             : (csdDecoded.Size + 1) * 1024);

                    blockSize = (uint)Math.Pow(2, csdDecoded.ReadBlockLength);

                    // Structure >=1 for SDHC/SDXC, so that's block addressed
                    byteAddressed = csdDecoded.Structure == 0;
                    mediaTags.Add(MediaTagType.SD_CSD, null);

                    physicalBlockSize = blockSize;

                    if (blockSize != 512)
                    {
                        uint ratio = blockSize / 512;
                        blocks   *= ratio;
                        blockSize = 512;
                    }
                }
                else
                {
                    _errorLog?.WriteLine("Read CSD", _dev.Error, _dev.LastError, response);
                    csd = null;
                }

                UpdateStatus?.Invoke("Reading OCR");
                _dumpLog.WriteLine("Reading OCR");
                sense = _dev.ReadSdocr(out ocr, out response, timeout, out duration);

                if (sense)
                {
                    _errorLog?.WriteLine("Read OCR", _dev.Error, _dev.LastError, response);
                    ocr = null;
                }
                else
                {
                    mediaTags.Add(MediaTagType.SD_OCR, null);
                }

                UpdateStatus?.Invoke("Reading SCR");
                _dumpLog.WriteLine("Reading SCR");
                sense = _dev.ReadScr(out scr, out response, timeout, out duration);

                if (sense)
                {
                    _errorLog?.WriteLine("Read SCR", _dev.Error, _dev.LastError, response);
                    scr = null;
                }
                else
                {
                    supportsCmd23 = Decoders.SecureDigital.Decoders.DecodeSCR(scr)?.CommandSupport.
                                    HasFlag(CommandSupport.SetBlockCount) ?? false;

                    mediaTags.Add(MediaTagType.SD_SCR, null);
                }

                break;
            }
            }

            UpdateStatus?.Invoke("Reading CID");
            _dumpLog.WriteLine("Reading CID");
            sense = _dev.ReadCid(out byte[] cid, out response, timeout, out duration);

            if (sense)
            {
                _errorLog?.WriteLine("Read CID", _dev.Error, _dev.LastError, response);
                cid = null;
            }
            else
            {
                mediaTags.Add(_dev.Type == DeviceType.SecureDigital ? MediaTagType.SD_CID : MediaTagType.MMC_CID, null);
            }

            DateTime start;
            DateTime end;
            double   totalDuration = 0;
            double   currentSpeed  = 0;
            double   maxSpeed      = double.MinValue;
            double   minSpeed      = double.MaxValue;

            if (blocks == 0)
            {
                _dumpLog.WriteLine("Unable to get device size.");
                StoppingErrorMessage?.Invoke("Unable to get device size.");

                return;
            }

            UpdateStatus?.Invoke($"Device reports {blocks} blocks.");
            _dumpLog.WriteLine("Device reports {0} blocks.", blocks);

            byte[] cmdBuf;
            bool   error;

            if (blocksToRead > _maximumReadable)
            {
                blocksToRead = (ushort)_maximumReadable;
            }

            if (supportsCmd23 && blocksToRead > 1)
            {
                sense = _dev.ReadWithBlockCount(out cmdBuf, out _, 0, blockSize, 1, byteAddressed, timeout,
                                                out duration);

                if (sense || _dev.Error)
                {
                    supportsCmd23 = false;
                }

                // Need to restart device, otherwise is it just busy streaming data with no one listening
                sense = _dev.ReOpen();

                if (sense)
                {
                    StoppingErrorMessage?.Invoke($"Error {_dev.LastError} reopening device.");

                    return;
                }
            }

            if (supportsCmd23 && blocksToRead > 1)
            {
                while (true)
                {
                    error = _dev.ReadWithBlockCount(out cmdBuf, out _, 0, blockSize, blocksToRead, byteAddressed,
                                                    timeout, out duration);

                    if (error)
                    {
                        blocksToRead /= 2;
                    }

                    if (!error ||
                        blocksToRead == 1)
                    {
                        break;
                    }
                }

                if (error)
                {
                    _dumpLog.WriteLine("ERROR: Cannot get blocks to read, device error {0}.", _dev.LastError);

                    StoppingErrorMessage?.
                    Invoke($"Device error {_dev.LastError} trying to guess ideal transfer length.");

                    return;
                }
            }

            if (supportsCmd23 || blocksToRead == 1)
            {
                UpdateStatus?.Invoke($"Device can read {blocksToRead} blocks at a time.");
                _dumpLog.WriteLine("Device can read {0} blocks at a time.", blocksToRead);
            }
            else if (_useBufferedReads)
            {
                UpdateStatus?.Invoke($"Device can read {blocksToRead} blocks at a time using OS buffered reads.");
                _dumpLog.WriteLine("Device can read {0} blocks at a time using OS buffered reads.", blocksToRead);
            }
            else
            {
                UpdateStatus?.Invoke($"Device can read {blocksToRead} blocks using sequential commands.");
                _dumpLog.WriteLine("Device can read {0} blocks using sequential commands.", blocksToRead);
            }

            if (_skip < blocksToRead)
            {
                _skip = blocksToRead;
            }

            DumpHardwareType currentTry = null;
            ExtentsULong     extents    = null;

            ResumeSupport.Process(true, false, blocks, _dev.Manufacturer, _dev.Model, _dev.Serial, _dev.PlatformId,
                                  ref _resume, ref currentTry, ref extents, _dev.FirmwareRevision, _private);

            if (currentTry == null ||
                extents == null)
            {
                StoppingErrorMessage?.Invoke("Could not process resume file, not continuing...");

                return;
            }

            bool ret = true;

            foreach (MediaTagType tag in mediaTags.Keys.Where(tag => !_outputPlugin.SupportedMediaTags.Contains(tag)))
            {
                ret = false;
                _dumpLog.WriteLine($"Output format does not support {tag}.");
                ErrorMessage?.Invoke($"Output format does not support {tag}.");
            }

            if (!ret)
            {
                if (_force)
                {
                    _dumpLog.WriteLine("Several media tags not supported, continuing...");
                    ErrorMessage?.Invoke("Several media tags not supported, continuing...");
                }
                else
                {
                    _dumpLog.WriteLine("Several media tags not supported, not continuing...");
                    StoppingErrorMessage?.Invoke("Several media tags not supported, not continuing...");

                    return;
                }
            }

            var mhddLog = new MhddLog(_outputPrefix + ".mhddlog.bin", _dev, blocks, blockSize, blocksToRead, _private);
            var ibgLog  = new IbgLog(_outputPrefix + ".ibg", sdProfile);

            ret = _outputPlugin.Create(_outputPath,
                                       _dev.Type == DeviceType.SecureDigital ? MediaType.SecureDigital : MediaType.MMC,
                                       _formatOptions, blocks, blockSize);

            // Cannot create image
            if (!ret)
            {
                _dumpLog.WriteLine("Error creating output image, not continuing.");
                _dumpLog.WriteLine(_outputPlugin.ErrorMessage);

                StoppingErrorMessage?.Invoke("Error creating output image, not continuing." + Environment.NewLine +
                                             _outputPlugin.ErrorMessage);

                return;
            }

            if (cid != null)
            {
                if (_dev.Type == DeviceType.SecureDigital && _private)
                {
                    // Clear serial number and manufacturing date
                    cid[9]  = 0;
                    cid[10] = 0;
                    cid[11] = 0;
                    cid[12] = 0;
                    cid[13] = 0;
                    cid[14] = 0;
                }
                else if (_dev.Type == DeviceType.MMC && _private)
                {
                    // Clear serial number and manufacturing date
                    cid[10] = 0;
                    cid[11] = 0;
                    cid[12] = 0;
                    cid[13] = 0;
                    cid[14] = 0;
                }

                ret =
                    _outputPlugin.WriteMediaTag(cid,
                                                _dev.Type == DeviceType.SecureDigital ? MediaTagType.SD_CID
                                                    : MediaTagType.MMC_CID);

                // Cannot write CID to image
                if (!ret &&
                    !_force)
                {
                    _dumpLog.WriteLine("Cannot write CID to output image.");

                    StoppingErrorMessage?.Invoke("Cannot write CID to output image." + Environment.NewLine +
                                                 _outputPlugin.ErrorMessage);

                    return;
                }
            }

            if (csd != null)
            {
                ret =
                    _outputPlugin.WriteMediaTag(csd,
                                                _dev.Type == DeviceType.SecureDigital ? MediaTagType.SD_CSD
                                                    : MediaTagType.MMC_CSD);

                // Cannot write CSD to image
                if (!ret &&
                    !_force)
                {
                    _dumpLog.WriteLine("Cannot write CSD to output image.");

                    StoppingErrorMessage?.Invoke("Cannot write CSD to output image." + Environment.NewLine +
                                                 _outputPlugin.ErrorMessage);

                    return;
                }
            }

            if (ecsd != null)
            {
                ret = _outputPlugin.WriteMediaTag(ecsd, MediaTagType.MMC_ExtendedCSD);

                // Cannot write Extended CSD to image
                if (!ret &&
                    !_force)
                {
                    _dumpLog.WriteLine("Cannot write Extended CSD to output image.");

                    StoppingErrorMessage?.Invoke("Cannot write Extended CSD to output image." + Environment.NewLine +
                                                 _outputPlugin.ErrorMessage);

                    return;
                }
            }

            if (ocr != null)
            {
                ret =
                    _outputPlugin.WriteMediaTag(ocr,
                                                _dev.Type == DeviceType.SecureDigital ? MediaTagType.SD_OCR
                                                    : MediaTagType.MMC_OCR);

                // Cannot write OCR to image
                if (!ret &&
                    !_force)
                {
                    _dumpLog.WriteLine("Cannot write OCR to output image.");

                    StoppingErrorMessage?.Invoke("Cannot write OCR to output image." + Environment.NewLine +
                                                 _outputPlugin.ErrorMessage);

                    return;
                }
            }

            if (scr != null)
            {
                ret = _outputPlugin.WriteMediaTag(scr, MediaTagType.SD_SCR);

                // Cannot write SCR to image
                if (!ret &&
                    !_force)
                {
                    _dumpLog.WriteLine("Cannot write SCR to output image.");

                    StoppingErrorMessage?.Invoke("Cannot write SCR to output image." + Environment.NewLine +
                                                 _outputPlugin.ErrorMessage);

                    return;
                }
            }

            if (_resume.NextBlock > 0)
            {
                UpdateStatus?.Invoke($"Resuming from block {_resume.NextBlock}.");
                _dumpLog.WriteLine("Resuming from block {0}.", _resume.NextBlock);
            }

            start = DateTime.UtcNow;
            double   imageWriteDuration = 0;
            bool     newTrim            = false;
            DateTime timeSpeedStart     = DateTime.UtcNow;
            ulong    sectorSpeedStart   = 0;

            InitProgress?.Invoke();

            for (ulong i = _resume.NextBlock; i < blocks; i += blocksToRead)
            {
                if (_aborted)
                {
                    currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                    UpdateStatus?.Invoke("Aborted!");
                    _dumpLog.WriteLine("Aborted!");

                    break;
                }

                if (blocks - i < blocksToRead)
                {
                    blocksToRead = (byte)(blocks - i);
                }

                if (currentSpeed > maxSpeed &&
                    currentSpeed > 0)
                {
                    maxSpeed = currentSpeed;
                }

                if (currentSpeed < minSpeed &&
                    currentSpeed > 0)
                {
                    minSpeed = currentSpeed;
                }

                UpdateProgress?.Invoke($"Reading sector {i} of {blocks} ({currentSpeed:F3} MiB/sec.)", (long)i,
                                       (long)blocks);

                if (blocksToRead == 1)
                {
                    error = _dev.ReadSingleBlock(out cmdBuf, out _, (uint)i, blockSize, byteAddressed, timeout,
                                                 out duration);
                }
                else if (supportsCmd23)
                {
                    error = _dev.ReadWithBlockCount(out cmdBuf, out _, (uint)i, blockSize, blocksToRead, byteAddressed,
                                                    timeout, out duration);
                }
                else if (_useBufferedReads)
                {
                    error = _dev.BufferedOsRead(out cmdBuf, (long)(i * blockSize), blockSize * blocksToRead,
                                                out duration);
                }
                else
                {
                    error = _dev.ReadMultipleUsingSingle(out cmdBuf, out _, (uint)i, blockSize, blocksToRead,
                                                         byteAddressed, timeout, out duration);
                }

                if (!error)
                {
                    mhddLog.Write(i, duration);
                    ibgLog.Write(i, currentSpeed * 1024);
                    DateTime writeStart = DateTime.Now;
                    _outputPlugin.WriteSectors(cmdBuf, i, blocksToRead);
                    imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds;
                    extents.Add(i, blocksToRead, true);
                }
                else
                {
                    _errorLog?.WriteLine(i, _dev.Error, _dev.LastError, byteAddressed, response);

                    if (i + _skip > blocks)
                    {
                        _skip = (uint)(blocks - i);
                    }

                    for (ulong b = i; b < i + _skip; b++)
                    {
                        _resume.BadBlocks.Add(b);
                    }

                    mhddLog.Write(i, duration < 500 ? 65535 : duration);

                    ibgLog.Write(i, 0);
                    DateTime writeStart = DateTime.Now;
                    _outputPlugin.WriteSectors(new byte[blockSize * _skip], i, _skip);
                    imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds;
                    _dumpLog.WriteLine("Skipping {0} blocks from errored block {1}.", _skip, i);
                    i      += _skip - blocksToRead;
                    newTrim = true;
                }

                sectorSpeedStart += blocksToRead;
                _resume.NextBlock = i + blocksToRead;

                double elapsed = (DateTime.UtcNow - timeSpeedStart).TotalSeconds;

                if (elapsed < 1)
                {
                    continue;
                }

                currentSpeed     = sectorSpeedStart * blockSize / (1048576 * elapsed);
                sectorSpeedStart = 0;
                timeSpeedStart   = DateTime.UtcNow;
            }

            _resume.BadBlocks = _resume.BadBlocks.Distinct().ToList();

            end = DateTime.Now;
            EndProgress?.Invoke();
            mhddLog.Close();

            ibgLog.Close(_dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024,
                         blockSize * (double)(blocks + 1) / 1024 / (totalDuration / 1000), _devicePath);

            UpdateStatus?.Invoke($"Dump finished in {(end - start).TotalSeconds} seconds.");

            UpdateStatus?.
            Invoke($"Average dump speed {(double)blockSize * (double)(blocks + 1) / 1024 / (totalDuration / 1000):F3} KiB/sec.");

            UpdateStatus?.
            Invoke($"Average write speed {(double)blockSize * (double)(blocks + 1) / 1024 / imageWriteDuration:F3} KiB/sec.");

            _dumpLog.WriteLine("Dump finished in {0} seconds.", (end - start).TotalSeconds);

            _dumpLog.WriteLine("Average dump speed {0:F3} KiB/sec.",
                               (double)blockSize * (double)(blocks + 1) / 1024 / (totalDuration / 1000));

            _dumpLog.WriteLine("Average write speed {0:F3} KiB/sec.",
                               (double)blockSize * (double)(blocks + 1) / 1024 / imageWriteDuration);

            #region Trimming
            if (_resume.BadBlocks.Count > 0 &&
                !_aborted &&
                _trim &&
                newTrim)
            {
                start = DateTime.UtcNow;
                UpdateStatus?.Invoke("Trimming skipped sectors");
                _dumpLog.WriteLine("Trimming skipped sectors");

                ulong[] tmpArray = _resume.BadBlocks.ToArray();
                InitProgress?.Invoke();

                foreach (ulong badSector in tmpArray)
                {
                    if (_aborted)
                    {
                        currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                        UpdateStatus?.Invoke("Aborted!");
                        _dumpLog.WriteLine("Aborted!");

                        break;
                    }

                    PulseProgress?.Invoke($"Trimming sector {badSector}");

                    error = _dev.ReadSingleBlock(out cmdBuf, out response, (uint)badSector, blockSize, byteAddressed,
                                                 timeout, out duration);

                    totalDuration += duration;

                    if (error)
                    {
                        _errorLog?.WriteLine(badSector, _dev.Error, _dev.LastError, byteAddressed, response);

                        continue;
                    }

                    _resume.BadBlocks.Remove(badSector);
                    extents.Add(badSector);
                    _outputPlugin.WriteSector(cmdBuf, badSector);
                }

                EndProgress?.Invoke();
                end = DateTime.UtcNow;
                UpdateStatus?.Invoke($"Trimming finished in {(end - start).TotalSeconds} seconds.");
                _dumpLog.WriteLine("Trimming finished in {0} seconds.", (end - start).TotalSeconds);
            }
            #endregion Trimming

            #region Error handling
            if (_resume.BadBlocks.Count > 0 &&
                !_aborted &&
                _retryPasses > 0)
            {
                int  pass              = 1;
                bool forward           = true;
                bool runningPersistent = false;

                InitProgress?.Invoke();
repeatRetryLba:
                ulong[] tmpArray = _resume.BadBlocks.ToArray();

                foreach (ulong badSector in tmpArray)
                {
                    if (_aborted)
                    {
                        currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                        UpdateStatus?.Invoke("Aborted!");
                        _dumpLog.WriteLine("Aborted!");

                        break;
                    }

                    PulseProgress?.Invoke(string.Format("Retrying sector {0}, pass {1}, {3}{2}", badSector, pass,
                                                        forward ? "forward" : "reverse",
                                                        runningPersistent ? "recovering partial data, " : ""));

                    error = _dev.ReadSingleBlock(out cmdBuf, out response, (uint)badSector, blockSize, byteAddressed,
                                                 timeout, out duration);

                    totalDuration += duration;

                    if (error)
                    {
                        _errorLog?.WriteLine(badSector, _dev.Error, _dev.LastError, byteAddressed, response);
                    }

                    if (!error)
                    {
                        _resume.BadBlocks.Remove(badSector);
                        extents.Add(badSector);
                        _outputPlugin.WriteSector(cmdBuf, badSector);
                        UpdateStatus?.Invoke($"Correctly retried block {badSector} in pass {pass}.");
                        _dumpLog.WriteLine("Correctly retried block {0} in pass {1}.", badSector, pass);
                    }
                    else if (runningPersistent)
                    {
                        _outputPlugin.WriteSector(cmdBuf, badSector);
                    }
                }

                if (pass < _retryPasses &&
                    !_aborted &&
                    _resume.BadBlocks.Count > 0)
                {
                    pass++;
                    forward = !forward;
                    _resume.BadBlocks.Sort();

                    if (!forward)
                    {
                        _resume.BadBlocks.Reverse();
                    }

                    goto repeatRetryLba;
                }

                EndProgress?.Invoke();
            }
            #endregion Error handling

            currentTry.Extents = ExtentsConverter.ToMetadata(extents);

            _outputPlugin.SetDumpHardware(_resume.Tries);

            // TODO: Drive info
            var metadata = new CommonTypes.Structs.ImageInfo
            {
                Application        = "Aaru",
                ApplicationVersion = Version.GetVersion()
            };

            if (!_outputPlugin.SetMetadata(metadata))
            {
                ErrorMessage?.Invoke("Error {0} setting metadata, continuing..." + Environment.NewLine +
                                     _outputPlugin.ErrorMessage);
            }

            if (_preSidecar != null)
            {
                _outputPlugin.SetCicmMetadata(_preSidecar);
            }

            _dumpLog.WriteLine("Closing output file.");
            UpdateStatus?.Invoke("Closing output file.");
            DateTime closeStart = DateTime.Now;
            _outputPlugin.Close();
            DateTime closeEnd = DateTime.Now;
            UpdateStatus?.Invoke($"Closed in {(closeEnd - closeStart).TotalSeconds} seconds.");
            _dumpLog.WriteLine("Closed in {0} seconds.", (closeEnd - closeStart).TotalSeconds);

            if (_aborted)
            {
                UpdateStatus?.Invoke("Aborted!");
                _dumpLog.WriteLine("Aborted!");

                return;
            }

            double totalChkDuration = 0;

            if (_metadata)
            {
                UpdateStatus?.Invoke("Creating sidecar.");
                _dumpLog.WriteLine("Creating sidecar.");
                var         filters     = new FiltersList();
                IFilter     filter      = filters.GetFilter(_outputPath);
                IMediaImage inputPlugin = ImageFormat.Detect(filter);

                if (!inputPlugin.Open(filter))
                {
                    StoppingErrorMessage?.Invoke("Could not open created image.");
                }

                DateTime chkStart = DateTime.UtcNow;
                _sidecarClass = new Sidecar(inputPlugin, _outputPath, filter.Id, _encoding);
                _sidecarClass.InitProgressEvent    += InitProgress;
                _sidecarClass.UpdateProgressEvent  += UpdateProgress;
                _sidecarClass.EndProgressEvent     += EndProgress;
                _sidecarClass.InitProgressEvent2   += InitProgress2;
                _sidecarClass.UpdateProgressEvent2 += UpdateProgress2;
                _sidecarClass.EndProgressEvent2    += EndProgress2;
                _sidecarClass.UpdateStatusEvent    += UpdateStatus;
                CICMMetadataType sidecar = _sidecarClass.Create();

                if (_preSidecar != null)
                {
                    _preSidecar.BlockMedia = sidecar.BlockMedia;
                    sidecar = _preSidecar;
                }

                end = DateTime.UtcNow;

                totalChkDuration = (end - chkStart).TotalMilliseconds;
                UpdateStatus?.Invoke($"Sidecar created in {(end - chkStart).TotalSeconds} seconds.");

                UpdateStatus?.
                Invoke($"Average checksum speed {(double)blockSize * (double)(blocks + 1) / 1024 / (totalChkDuration / 1000):F3} KiB/sec.");

                _dumpLog.WriteLine("Sidecar created in {0} seconds.", (end - chkStart).TotalSeconds);

                _dumpLog.WriteLine("Average checksum speed {0:F3} KiB/sec.",
                                   (double)blockSize * (double)(blocks + 1) / 1024 / (totalChkDuration / 1000));

                (string type, string subType)xmlType = (null, null);

                switch (_dev.Type)
                {
                case DeviceType.MMC:
                    xmlType = CommonTypes.Metadata.MediaType.MediaTypeToString(MediaType.MMC);

                    sidecar.BlockMedia[0].Dimensions = Dimensions.DimensionsFromMediaType(MediaType.MMC);

                    break;

                case DeviceType.SecureDigital:
                    CommonTypes.Metadata.MediaType.MediaTypeToString(MediaType.SecureDigital);
                    sidecar.BlockMedia[0].Dimensions = Dimensions.DimensionsFromMediaType(MediaType.SecureDigital);

                    break;
                }

                sidecar.BlockMedia[0].DiskType    = xmlType.type;
                sidecar.BlockMedia[0].DiskSubType = xmlType.subType;

                // TODO: Implement device firmware revision
                sidecar.BlockMedia[0].LogicalBlocks     = blocks;
                sidecar.BlockMedia[0].PhysicalBlockSize = physicalBlockSize > 0 ? physicalBlockSize : blockSize;
                sidecar.BlockMedia[0].LogicalBlockSize  = blockSize;
                sidecar.BlockMedia[0].Manufacturer      = _dev.Manufacturer;
                sidecar.BlockMedia[0].Model             = _dev.Model;

                if (!_private)
                {
                    sidecar.BlockMedia[0].Serial = _dev.Serial;
                }

                sidecar.BlockMedia[0].Size = blocks * blockSize;

                UpdateStatus?.Invoke("Writing metadata sidecar");

                var xmlFs = new FileStream(_outputPrefix + ".cicm.xml", FileMode.Create);

                var xmlSer = new XmlSerializer(typeof(CICMMetadataType));
                xmlSer.Serialize(xmlFs, sidecar);
                xmlFs.Close();
            }

            UpdateStatus?.Invoke("");

            UpdateStatus?.
            Invoke($"Took a total of {(end - start).TotalSeconds:F3} seconds ({totalDuration / 1000:F3} processing commands, {totalChkDuration / 1000:F3} checksumming, {imageWriteDuration:F3} writing, {(closeEnd - closeStart).TotalSeconds:F3} closing).");

            UpdateStatus?.
            Invoke($"Average speed: {(double)blockSize * (double)(blocks + 1) / 1048576 / (totalDuration / 1000):F3} MiB/sec.");

            if (maxSpeed > 0)
            {
                UpdateStatus?.Invoke($"Fastest speed burst: {maxSpeed:F3} MiB/sec.");
            }

            if (minSpeed > 0 &&
                minSpeed < double.MaxValue)
            {
                UpdateStatus?.Invoke($"Slowest speed burst: {minSpeed:F3} MiB/sec.");
            }

            UpdateStatus?.Invoke($"{_resume.BadBlocks.Count} sectors could not be read.");
            UpdateStatus?.Invoke("");

            if (_resume.BadBlocks.Count > 0)
            {
                _resume.BadBlocks.Sort();
            }

            switch (_dev.Type)
            {
            case DeviceType.MMC:
                Statistics.AddMedia(MediaType.MMC, true);

                break;

            case DeviceType.SecureDigital:
                Statistics.AddMedia(MediaType.SecureDigital, true);

                break;
            }
        }