コード例 #1
0
        public HttpResponseMessage UploadReport()
        {
            HttpResponseMessage response = new HttpResponseMessage {
                StatusCode = HttpStatusCode.OK
            };

            try
            {
                DeviceReport newReport = new DeviceReport();
                HttpRequest  request   = HttpContext.Current.Request;

                XmlSerializer xs = new XmlSerializer(newReport.GetType());
                newReport = (DeviceReport)xs.Deserialize(request.InputStream);

                if (newReport == null)
                {
                    response.Content = new StringContent("notstats", Encoding.UTF8, "text/plain");
                    return(response);
                }

                Random rng      = new Random();
                string filename = $"NewReport_{DateTime.UtcNow:yyyyMMddHHmmssfff}_{rng.Next()}.xml";
                while (File.Exists(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(),
                                                "Upload", filename)))
                {
                    filename = $"NewReport_{DateTime.UtcNow:yyyyMMddHHmmssfff}_{rng.Next()}.xml";
                }

                FileStream newFile =
                    new
                    FileStream(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Upload", filename),
                               FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
                xs.Serialize(newFile, newReport);
                newFile.Close();

                response.Content = new StringContent("ok", Encoding.UTF8, "text/plain");
                return(response);
            }
            // ReSharper disable once RedundantCatchClause
            catch
            {
#if DEBUG
                throw;
#else
                response.Content = new StringContent("error", System.Text.Encoding.UTF8, "text/plain");
                return(response);
#endif
            }
        }
コード例 #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string manufacturer = Request.QueryString["manufacturer"];
                string model        = Request.QueryString["model"];
                string revision     = Request.QueryString["revision"];

                // Strip non-ascii, strip slashes and question marks
                if (manufacturer != null)
                {
                    manufacturer = Encoding
                                   .ASCII.GetString(Encoding.Convert(Encoding.UTF8, Encoding.ASCII,
                                                                     Encoding.UTF8.GetBytes(manufacturer))).Replace('/', '_')
                                   .Replace('\\', '_').Replace('?', '_');
                }
                if (model != null)
                {
                    model = Encoding
                            .ASCII.GetString(Encoding.Convert(Encoding.UTF8, Encoding.ASCII, Encoding.UTF8.GetBytes(model)))
                            .Replace('/', '_').Replace('\\', '_').Replace('?', '_');
                }
                if (revision != null)
                {
                    revision = Encoding
                               .ASCII.GetString(Encoding.Convert(Encoding.UTF8, Encoding.ASCII,
                                                                 Encoding.UTF8.GetBytes(revision))).Replace('/', '_')
                               .Replace('\\', '_').Replace('?', '_');
                }

                string xmlFile = null;
                if (!string.IsNullOrWhiteSpace(manufacturer) && !string.IsNullOrWhiteSpace(model) &&
                    !string.IsNullOrWhiteSpace(revision))
                {
                    xmlFile = manufacturer + "_" + model + "_" + revision + ".xml";
                }
                else if (!string.IsNullOrWhiteSpace(manufacturer) && !string.IsNullOrWhiteSpace(model))
                {
                    xmlFile = manufacturer + "_" + model + ".xml";
                }
                else if (!string.IsNullOrWhiteSpace(model) && !string.IsNullOrWhiteSpace(revision))
                {
                    xmlFile = model + "_" + revision + ".xml";
                }
                else if (!string.IsNullOrWhiteSpace(model))
                {
                    xmlFile = model + ".xml";
                }

                if (xmlFile == null ||
                    !File.Exists(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(),
                                              "Reports", xmlFile)))
                {
                    content.InnerHtml = "<b>Could not find the specified report</b>";
                    return;
                }

                lblManufacturer.Text = Request.QueryString["manufacturer"];
                lblModel.Text        = Request.QueryString["model"];
                lblRevision.Text     = Request.QueryString["revision"];

                DeviceReport  report = new DeviceReport();
                XmlSerializer xs     = new XmlSerializer(report.GetType());
                StreamReader  sr     =
                    new
                    StreamReader(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(),
                                              "Reports", xmlFile));
                report = (DeviceReport)xs.Deserialize(sr);
                sr.Close();

                if (report.USB != null)
                {
                    GetUsbDescriptions(report.USB.VendorID, report.USB.ProductID, out string usbVendorDescription,
                                       out string usbProductDescription);

                    lblUsbManufacturer.Text = HttpUtility.HtmlEncode(report.USB.Manufacturer);
                    lblUsbProduct.Text      = HttpUtility.HtmlEncode(report.USB.Product);
                    lblUsbVendor.Text       = $"0x{report.USB.VendorID:x4}";
                    if (usbVendorDescription != null)
                    {
                        lblUsbVendorDescription.Text = $"({HttpUtility.HtmlEncode(usbVendorDescription)})";
                    }
                    lblUsbProductId.Text = $"0x{report.USB.ProductID:x4}";
                    if (usbProductDescription != null)
                    {
                        lblUsbProductDescription.Text = $"({HttpUtility.HtmlEncode(usbProductDescription)})";
                    }
                }
                else
                {
                    divUsb.Visible = false;
                }

                if (report.FireWire != null)
                {
                    lblFirewireManufacturer.Text = HttpUtility.HtmlEncode(report.FireWire.Manufacturer);
                    lblFirewireProduct.Text      = HttpUtility.HtmlEncode(report.FireWire.Product);
                    lblFirewireVendor.Text       = $"0x{report.FireWire.VendorID:x8}";
                    lblFirewireProductId.Text    = $"0x{report.FireWire.ProductID:x8}";
                }
                else
                {
                    divFirewire.Visible = false;
                }

                if (report.PCMCIA != null)
                {
                    lblPcmciaManufacturer.Text     = HttpUtility.HtmlEncode(report.PCMCIA.Manufacturer);
                    lblPcmciaProduct.Text          = HttpUtility.HtmlEncode(report.PCMCIA.ProductName);
                    lblPcmciaManufacturerCode.Text = $"0x{report.PCMCIA.ManufacturerCode:x4}";
                    lblPcmciaCardCode.Text         = $"0x{report.PCMCIA.CardCode:x4}";
                    lblPcmciaCompliance.Text       = HttpUtility.HtmlEncode(report.PCMCIA.Compliance);
                    Tuple[] tuples = CIS.GetTuples(report.PCMCIA.CIS);
                    if (tuples != null)
                    {
                        Dictionary <string, string> decodedTuples = new Dictionary <string, string>();
                        foreach (Tuple tuple in tuples)
                        {
                            switch (tuple.Code)
                            {
                            case TupleCodes.CISTPL_NULL:
                            case TupleCodes.CISTPL_END:
                            case TupleCodes.CISTPL_MANFID:
                            case TupleCodes.CISTPL_VERS_1: break;

                            case TupleCodes.CISTPL_DEVICEGEO:
                            case TupleCodes.CISTPL_DEVICEGEO_A:
                                DeviceGeometryTuple geom = CIS.DecodeDeviceGeometryTuple(tuple.Data);
                                if (geom?.Geometries != null)
                                {
                                    foreach (DeviceGeometry geometry in geom.Geometries)
                                    {
                                        decodedTuples.Add("Device width",
                                                          $"{(1 << (geometry.CardInterface - 1)) * 8} bits");
                                        decodedTuples.Add("Erase block",
                                                          $"{(1 << (geometry.EraseBlockSize - 1)) * (1 << (geometry.Interleaving - 1))} bytes");
                                        decodedTuples.Add("Read block",
                                                          $"{(1 << (geometry.ReadBlockSize - 1)) * (1 << (geometry.Interleaving - 1))} bytes");
                                        decodedTuples.Add("Write block",
                                                          $"{(1 << (geometry.WriteBlockSize - 1)) * (1 << (geometry.Interleaving - 1))} bytes");
                                        decodedTuples.Add("Partition alignment",
                                                          $"{(1 << (geometry.EraseBlockSize - 1)) * (1 << (geometry.Interleaving - 1)) * (1 << (geometry.Partitions - 1))} bytes");
                                    }
                                }

                                break;

                            case TupleCodes.CISTPL_ALTSTR:
                            case TupleCodes.CISTPL_BAR:
                            case TupleCodes.CISTPL_BATTERY:
                            case TupleCodes.CISTPL_BYTEORDER:
                            case TupleCodes.CISTPL_CFTABLE_ENTRY:
                            case TupleCodes.CISTPL_CFTABLE_ENTRY_CB:
                            case TupleCodes.CISTPL_CHECKSUM:
                            case TupleCodes.CISTPL_CONFIG:
                            case TupleCodes.CISTPL_CONFIG_CB:
                            case TupleCodes.CISTPL_DATE:
                            case TupleCodes.CISTPL_DEVICE:
                            case TupleCodes.CISTPL_DEVICE_A:
                            case TupleCodes.CISTPL_DEVICE_OA:
                            case TupleCodes.CISTPL_DEVICE_OC:
                            case TupleCodes.CISTPL_EXTDEVIC:
                            case TupleCodes.CISTPL_FORMAT:
                            case TupleCodes.CISTPL_FORMAT_A:
                            case TupleCodes.CISTPL_FUNCE:
                            case TupleCodes.CISTPL_FUNCID:
                            case TupleCodes.CISTPL_GEOMETRY:
                            case TupleCodes.CISTPL_INDIRECT:
                            case TupleCodes.CISTPL_JEDEC_A:
                            case TupleCodes.CISTPL_JEDEC_C:
                            case TupleCodes.CISTPL_LINKTARGET:
                            case TupleCodes.CISTPL_LONGLINK_A:
                            case TupleCodes.CISTPL_LONGLINK_C:
                            case TupleCodes.CISTPL_LONGLINK_CB:
                            case TupleCodes.CISTPL_LONGLINK_MFC:
                            case TupleCodes.CISTPL_NO_LINK:
                            case TupleCodes.CISTPL_ORG:
                            case TupleCodes.CISTPL_PWR_MGMNT:
                            case TupleCodes.CISTPL_SPCL:
                            case TupleCodes.CISTPL_SWIL:
                            case TupleCodes.CISTPL_VERS_2:
                                decodedTuples.Add("Undecoded tuple ID", tuple.Code.ToString());
                                break;

                            default:
                                decodedTuples.Add("Unknown tuple ID", $"0x{(byte)tuple.Code:X2}");
                                break;
                            }
                        }

                        if (decodedTuples.Count > 0)
                        {
                            repPcmciaTuples.DataSource = decodedTuples;
                            repPcmciaTuples.DataBind();
                        }
                        else
                        {
                            repPcmciaTuples.Visible = false;
                        }
                    }
                    else
                    {
                        repPcmciaTuples.Visible = false;
                    }
                }
                else
                {
                    divPcmcia.Visible = false;
                }

                bool removable = true;
                testedMediaType[] testedMedia = null;
                bool ata      = false;
                bool atapi    = false;
                bool sscMedia = false;

                if (report.ATA != null || report.ATAPI != null)
                {
                    ata = true;
                    List <string> ataOneValue = new List <string>();
                    Dictionary <string, string> ataTwoValue = new Dictionary <string, string>();
                    ataType ataReport;

                    if (report.ATAPI != null)
                    {
                        lblAtapi.Text = "PI";
                        ataReport     = report.ATAPI;
                        atapi         = true;
                    }
                    else
                    {
                        ataReport = report.ATA;
                    }

                    bool cfa = report.CompactFlashSpecified && report.CompactFlash;

                    if (atapi && !cfa)
                    {
                        lblAtaDeviceType.Text = "ATAPI device";
                    }
                    else if (!atapi && cfa)
                    {
                        lblAtaDeviceType.Text = "CompactFlash device";
                    }
                    else
                    {
                        lblAtaDeviceType.Text = "ATA device";
                    }

                    Ata.Report(ataReport, cfa, atapi, ref removable, ref ataOneValue, ref ataTwoValue, ref testedMedia);

                    repAtaOne.DataSource = ataOneValue;
                    repAtaOne.DataBind();
                    repAtaTwo.DataSource = ataTwoValue;
                    repAtaTwo.DataBind();
                }
                else
                {
                    divAta.Visible = false;
                }

                if (report.SCSI != null)
                {
                    List <string> scsiOneValue            = new List <string>();
                    Dictionary <string, string> modePages = new Dictionary <string, string>();
                    Dictionary <string, string> evpdPages = new Dictionary <string, string>();

                    lblScsiVendor.Text =
                        VendorString.Prettify(report.SCSI.Inquiry.VendorIdentification) !=
                        report.SCSI.Inquiry.VendorIdentification
                            ? $"{report.SCSI.Inquiry.VendorIdentification} ({VendorString.Prettify(report.SCSI.Inquiry.VendorIdentification)})"
                            : report.SCSI.Inquiry.VendorIdentification;
                    lblScsiProduct.Text  = report.SCSI.Inquiry.ProductIdentification;
                    lblScsiRevision.Text = report.SCSI.Inquiry.ProductRevisionLevel;

                    scsiOneValue.AddRange(ScsiInquiry.Report(report.SCSI.Inquiry));

                    if (report.SCSI.SupportsModeSense6)
                    {
                        scsiOneValue.Add("Device supports MODE SENSE (6)");
                    }
                    if (report.SCSI.SupportsModeSense10)
                    {
                        scsiOneValue.Add("Device supports MODE SENSE (10)");
                    }
                    if (report.SCSI.SupportsModeSubpages)
                    {
                        scsiOneValue.Add("Device supports MODE SENSE subpages");
                    }

                    if (report.SCSI.ModeSense != null)
                    {
                        ScsiModeSense.Report(report.SCSI.ModeSense, report.SCSI.Inquiry.VendorIdentification,
                                             report.SCSI.Inquiry.PeripheralDeviceType, ref scsiOneValue, ref modePages);
                    }

                    if (modePages.Count > 0)
                    {
                        repModeSense.DataSource = modePages;
                        repModeSense.DataBind();
                    }
                    else
                    {
                        divScsiModeSense.Visible = false;
                    }

                    if (report.SCSI.EVPDPages != null)
                    {
                        ScsiEvpd.Report(report.SCSI.EVPDPages, report.SCSI.Inquiry.VendorIdentification, ref evpdPages);
                    }

                    if (evpdPages.Count > 0)
                    {
                        repEvpd.DataSource = evpdPages;
                        repEvpd.DataBind();
                    }
                    else
                    {
                        divScsiEvpd.Visible = false;
                    }

                    divScsiMmcMode.Visible     = false;
                    divScsiMmcFeatures.Visible = false;
                    divScsiSsc.Visible         = false;

                    if (report.SCSI.MultiMediaDevice != null)
                    {
                        testedMedia = report.SCSI.MultiMediaDevice.TestedMedia;

                        if (report.SCSI.MultiMediaDevice.ModeSense2A != null)
                        {
                            List <string> mmcModeOneValue = new List <string>();
                            ScsiMmcMode.Report(report.SCSI.MultiMediaDevice.ModeSense2A, ref mmcModeOneValue);
                            if (mmcModeOneValue.Count > 0)
                            {
                                divScsiMmcMode.Visible    = true;
                                repScsiMmcMode.DataSource = mmcModeOneValue;
                                repScsiMmcMode.DataBind();
                            }
                        }

                        if (report.SCSI.MultiMediaDevice.Features != null)
                        {
                            List <string> mmcFeaturesOneValue = new List <string>();
                            ScsiMmcFeatures.Report(report.SCSI.MultiMediaDevice.Features, ref mmcFeaturesOneValue);
                            if (mmcFeaturesOneValue.Count > 0)
                            {
                                divScsiMmcFeatures.Visible    = true;
                                repScsiMmcFeatures.DataSource = mmcFeaturesOneValue;
                                repScsiMmcFeatures.DataBind();
                            }
                        }
                    }
                    else if (report.SCSI.SequentialDevice != null)
                    {
                        divScsiSsc.Visible = true;

                        lblScsiSscGranularity.Text = report.SCSI.SequentialDevice.BlockSizeGranularitySpecified
                                                         ? report.SCSI.SequentialDevice.BlockSizeGranularity.ToString()
                                                         : "Unspecified";

                        lblScsiSscMaxBlock.Text = report.SCSI.SequentialDevice.MaxBlockLengthSpecified
                                                      ? report.SCSI.SequentialDevice.MaxBlockLength.ToString()
                                                      : "Unspecified";

                        lblScsiSscMinBlock.Text = report.SCSI.SequentialDevice.MinBlockLengthSpecified
                                                      ? report.SCSI.SequentialDevice.MinBlockLength.ToString()
                                                      : "Unspecified";

                        if (report.SCSI.SequentialDevice.SupportedDensities != null)
                        {
                            repScsiSscDensities.DataSource = report.SCSI.SequentialDevice.SupportedDensities;
                            repScsiSscDensities.DataBind();
                        }
                        else
                        {
                            repScsiSscDensities.Visible = false;
                        }

                        if (report.SCSI.SequentialDevice.SupportedMediaTypes != null)
                        {
                            repScsiSscMedias.DataSource = report.SCSI.SequentialDevice.SupportedMediaTypes;
                            repScsiSscMedias.DataBind();
                        }
                        else
                        {
                            repScsiSscMedias.Visible = false;
                        }

                        if (report.SCSI.SequentialDevice.TestedMedia != null)
                        {
                            List <string> mediaOneValue = new List <string>();
                            SscTestedMedia.Report(report.SCSI.SequentialDevice.TestedMedia, ref mediaOneValue);
                            if (mediaOneValue.Count > 0)
                            {
                                sscMedia = true;
                                repTestedMedia.DataSource = mediaOneValue;
                                repTestedMedia.DataBind();
                            }
                            else
                            {
                                divTestedMedia.Visible = false;
                            }
                        }
                        else
                        {
                            divTestedMedia.Visible = false;
                        }
                    }
                    else if (report.SCSI.ReadCapabilities != null)
                    {
                        removable = false;
                        scsiOneValue.Add("");

                        if (report.SCSI.ReadCapabilities.BlocksSpecified &&
                            report.SCSI.ReadCapabilities.BlockSizeSpecified)
                        {
                            scsiOneValue
                            .Add($"Device has {report.SCSI.ReadCapabilities.Blocks} blocks of {report.SCSI.ReadCapabilities.BlockSize} bytes each");

                            if (report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize / 1024 /
                                1024 > 1000000)
                            {
                                scsiOneValue
                                .Add($"Device size: {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize} bytes, {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize / 1000 / 1000 / 1000 / 1000} Tb, {(double)(report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize) / 1024 / 1024 / 1024 / 1024:F2} TiB");
                            }
                            else if (report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize /
                                     1024 / 1024 > 1000)
                            {
                                scsiOneValue
                                .Add($"Device size: {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize} bytes, {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize / 1000 / 1000 / 1000} Gb, {(double)(report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize) / 1024 / 1024 / 1024:F2} GiB");
                            }
                            else
                            {
                                scsiOneValue
                                .Add($"Device size: {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize} bytes, {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize / 1000 / 1000} Mb, {(double)(report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize) / 1024 / 1024:F2} MiB");
                            }
                        }

                        if (report.SCSI.ReadCapabilities.MediumTypeSpecified)
                        {
                            scsiOneValue.Add($"Medium type code: {report.SCSI.ReadCapabilities.MediumType:X2}h");
                        }
                        if (report.SCSI.ReadCapabilities.DensitySpecified)
                        {
                            scsiOneValue.Add($"Density code: {report.SCSI.ReadCapabilities.Density:X2}h");
                        }
                        if ((report.SCSI.ReadCapabilities.SupportsReadLong ||
                             report.SCSI.ReadCapabilities.SupportsReadLong16) &&
                            report.SCSI.ReadCapabilities.LongBlockSizeSpecified)
                        {
                            scsiOneValue.Add($"Long block size: {report.SCSI.ReadCapabilities.LongBlockSize} bytes");
                        }
                        if (report.SCSI.ReadCapabilities.SupportsReadCapacity)
                        {
                            scsiOneValue.Add("Device supports READ CAPACITY (10) command.");
                        }
                        if (report.SCSI.ReadCapabilities.SupportsReadCapacity16)
                        {
                            scsiOneValue.Add("Device supports READ CAPACITY (16) command.");
                        }
                        if (report.SCSI.ReadCapabilities.SupportsRead)
                        {
                            scsiOneValue.Add("Device supports READ (6) command.");
                        }
                        if (report.SCSI.ReadCapabilities.SupportsRead10)
                        {
                            scsiOneValue.Add("Device supports READ (10) command.");
                        }
                        if (report.SCSI.ReadCapabilities.SupportsRead12)
                        {
                            scsiOneValue.Add("Device supports READ (12) command.");
                        }
                        if (report.SCSI.ReadCapabilities.SupportsRead16)
                        {
                            scsiOneValue.Add("Device supports READ (16) command.");
                        }
                        if (report.SCSI.ReadCapabilities.SupportsReadLong)
                        {
                            scsiOneValue.Add("Device supports READ LONG (10) command.");
                        }
                        if (report.SCSI.ReadCapabilities.SupportsReadLong16)
                        {
                            scsiOneValue.Add("Device supports READ LONG (16) command.");
                        }
                    }
                    else
                    {
                        testedMedia = report.SCSI.RemovableMedias;
                    }

                    repScsi.DataSource = scsiOneValue;
                    repScsi.DataBind();
                }
                else
                {
                    divScsi.Visible = false;
                }

                if (report.MultiMediaCard != null)
                {
                    List <string> mmcOneValue = new List <string>();

                    if (report.MultiMediaCard.CID != null)
                    {
                        mmcOneValue.Add(Decoders.MMC.Decoders.PrettifyCID(report.MultiMediaCard.CID)
                                        .Replace("\n", "<br/>"));
                        mmcOneValue.Add("");
                    }

                    if (report.MultiMediaCard.CSD != null)
                    {
                        mmcOneValue.Add(Decoders.MMC.Decoders.PrettifyCSD(report.MultiMediaCard.CSD)
                                        .Replace("\n", "<br/>"));
                        mmcOneValue.Add("");
                    }

                    if (report.MultiMediaCard.ExtendedCSD != null)
                    {
                        mmcOneValue.Add(Decoders.MMC.Decoders.PrettifyExtendedCSD(report.MultiMediaCard.ExtendedCSD)
                                        .Replace("\n", "<br/>"));
                        mmcOneValue.Add("");
                    }

                    if (report.MultiMediaCard.OCR != null)
                    {
                        mmcOneValue.Add(Decoders.MMC.Decoders.PrettifyCSD(report.MultiMediaCard.OCR)
                                        .Replace("\n", "<br/>"));
                        mmcOneValue.Add("");
                    }

                    repMMC.DataSource = mmcOneValue;
                    repMMC.DataBind();
                }
                else
                {
                    divMMC.Visible = false;
                }

                if (report.SecureDigital != null)
                {
                    List <string> sdOneValue = new List <string>();

                    if (report.SecureDigital.CID != null)
                    {
                        sdOneValue.Add(Decoders.SecureDigital.Decoders.PrettifyCID(report.SecureDigital.CID)
                                       .Replace("\n", "<br/>"));
                        sdOneValue.Add("");
                    }

                    if (report.SecureDigital.CSD != null)
                    {
                        sdOneValue.Add(Decoders.SecureDigital.Decoders.PrettifyCSD(report.SecureDigital.CSD)
                                       .Replace("\n", "<br/>"));
                        sdOneValue.Add("");
                    }

                    if (report.SecureDigital.SCR != null)
                    {
                        sdOneValue.Add(Decoders.SecureDigital.Decoders.PrettifySCR(report.SecureDigital.SCR)
                                       .Replace("\n", "<br/>"));
                        sdOneValue.Add("");
                    }

                    if (report.SecureDigital.OCR != null)
                    {
                        sdOneValue.Add(Decoders.SecureDigital.Decoders.PrettifyCSD(report.SecureDigital.OCR)
                                       .Replace("\n", "<br/>"));
                        sdOneValue.Add("");
                    }

                    repSD.DataSource = sdOneValue;
                    repSD.DataBind();
                }
                else
                {
                    divSD.Visible = false;
                }

                if (removable && !sscMedia && testedMedia != null)
                {
                    List <string> mediaOneValue = new List <string>();
                    TestedMedia.Report(testedMedia, ata, ref mediaOneValue);
                    if (mediaOneValue.Count > 0)
                    {
                        divTestedMedia.Visible    = true;
                        repTestedMedia.DataSource = mediaOneValue;
                        repTestedMedia.DataBind();
                    }
                    else
                    {
                        divTestedMedia.Visible = false;
                    }
                }
                else
                {
                    divTestedMedia.Visible &= sscMedia;
                }
            }
            catch (Exception)
            {
                content.InnerHtml = "<b>Could not load device report</b>";
#if DEBUG
                throw;
#endif
            }
        }
コード例 #3
0
    public ActionResult Index()
    {
        ViewBag.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

        try
        {
            if (System.IO.File.Exists(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(),
                                                   "Statistics", "Statistics.xml")))
            {
                try
                {
                    var statistics = new Stats();

                    var xs = new XmlSerializer(statistics.GetType());

                    FileStream fs =
                        WaitForFile(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(), "Statistics", "Statistics.xml"),
                                    FileMode.Open, FileAccess.Read, FileShare.Read);

                    statistics = (Stats)xs.Deserialize(fs);
                    fs.Close();

                    StatsConverter.Convert(statistics);

                    System.IO.File.Delete(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(),
                                                       "Statistics", "Statistics.xml"));
                }
                catch (XmlException)
                {
                    // Do nothing
                }
            }

            if (_ctx.OperatingSystems.Any())
            {
                List <NameValueStats> operatingSystems = new();

                foreach (OperatingSystem nvs in _ctx.OperatingSystems)
                {
                    operatingSystems.Add(new NameValueStats
                    {
                        name =
                            $"{DetectOS.GetPlatformName((PlatformID)Enum.Parse(typeof(PlatformID), nvs.Name), nvs.Version)}{(string.IsNullOrEmpty(nvs.Version) ? "" : " ")}{nvs.Version}",
                        Value = nvs.Count
                    });
                }

                ViewBag.repOperatingSystems = operatingSystems.OrderBy(os => os.name).ToList();
            }

            if (_ctx.Versions.Any())
            {
                List <NameValueStats> versions = new();

                foreach (Version nvs in _ctx.Versions)
                {
                    versions.Add(new NameValueStats
                    {
                        name  = nvs.Name == "previous" ? "Previous than 3.4.99.0" : nvs.Name,
                        Value = nvs.Count
                    });
                }

                ViewBag.repVersions = versions.OrderBy(ver => ver.name).ToList();
            }

            if (_ctx.Commands.Any())
            {
                ViewBag.repCommands = _ctx.Commands.OrderBy(c => c.Name).ToList();
            }

            if (_ctx.Filters.Any())
            {
                ViewBag.repFilters = _ctx.Filters.OrderBy(filter => filter.Name).ToList();
            }

            if (_ctx.MediaFormats.Any())
            {
                ViewBag.repMediaImages = _ctx.MediaFormats.OrderBy(filter => filter.Name).ToList();
            }

            if (_ctx.Partitions.Any())
            {
                ViewBag.repPartitions = _ctx.Partitions.OrderBy(filter => filter.Name).ToList();
            }

            if (_ctx.Filesystems.Any())
            {
                ViewBag.repFilesystems = _ctx.Filesystems.OrderBy(filter => filter.Name).ToList();
            }

            if (_ctx.Medias.Any())
            {
                List <MediaItem> realMedia    = new();
                List <MediaItem> virtualMedia = new();

                foreach (Media nvs in _ctx.Medias)
                {
                    try
                    {
                        (string type, string subType)mediaType =
                            MediaType.MediaTypeToString((CommonTypes.MediaType)Enum.Parse(typeof(CommonTypes.MediaType),
                                                                                          nvs.Type));

                        if (nvs.Real)
                        {
                            realMedia.Add(new MediaItem
                            {
                                Type    = mediaType.type,
                                SubType = mediaType.subType,
                                Count   = nvs.Count
                            });
                        }
                        else
                        {
                            virtualMedia.Add(new MediaItem
                            {
                                Type    = mediaType.type,
                                SubType = mediaType.subType,
                                Count   = nvs.Count
                            });
                        }
                    }
                    catch
                    {
                        if (nvs.Real)
                        {
                            realMedia.Add(new MediaItem
                            {
                                Type    = nvs.Type,
                                SubType = null,
                                Count   = nvs.Count
                            });
                        }
                        else
                        {
                            virtualMedia.Add(new MediaItem
                            {
                                Type    = nvs.Type,
                                SubType = null,
                                Count   = nvs.Count
                            });
                        }
                    }
                }

                if (realMedia.Count > 0)
                {
                    ViewBag.repRealMedia = realMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType).
                                           ToList();
                }

                if (virtualMedia.Count > 0)
                {
                    ViewBag.repVirtualMedia = virtualMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType).
                                              ToList();
                }
            }

            if (_ctx.DeviceStats.Any())
            {
                List <DeviceItem> devices = new();

                foreach (DeviceStat device in _ctx.DeviceStats.ToList())
                {
                    string xmlFile;

                    if (!string.IsNullOrWhiteSpace(device.Manufacturer) &&
                        !string.IsNullOrWhiteSpace(device.Model) &&
                        !string.IsNullOrWhiteSpace(device.Revision))
                    {
                        xmlFile = device.Manufacturer + "_" + device.Model + "_" + device.Revision + ".xml";
                    }
                    else if (!string.IsNullOrWhiteSpace(device.Manufacturer) &&
                             !string.IsNullOrWhiteSpace(device.Model))
                    {
                        xmlFile = device.Manufacturer + "_" + device.Model + ".xml";
                    }
                    else if (!string.IsNullOrWhiteSpace(device.Model) &&
                             !string.IsNullOrWhiteSpace(device.Revision))
                    {
                        xmlFile = device.Model + "_" + device.Revision + ".xml";
                    }
                    else
                    {
                        xmlFile = device.Model + ".xml";
                    }

                    xmlFile = xmlFile.Replace('/', '_').Replace('\\', '_').Replace('?', '_');

                    if (System.IO.File.Exists(Path.Combine(_env.ContentRootPath, "Reports", xmlFile)))
                    {
                        var deviceReport = new DeviceReport();

                        var xs = new XmlSerializer(deviceReport.GetType());

                        FileStream fs =
                            WaitForFile(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(), "Reports", xmlFile),
                                        FileMode.Open, FileAccess.Read, FileShare.Read);

                        deviceReport = (DeviceReport)xs.Deserialize(fs);
                        fs.Close();

                        var deviceReportV2 = new DeviceReportV2(deviceReport);

                        device.Report = _ctx.Devices.Add(new Device(deviceReportV2)).Entity;
                        _ctx.SaveChanges();

                        System.IO.File.
                        Delete(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(),
                                            "Reports", xmlFile));
                    }

                    devices.Add(new DeviceItem
                    {
                        Manufacturer = device.Manufacturer,
                        Model        = device.Model,
                        Revision     = device.Revision,
                        Bus          = device.Bus,
                        ReportId     = device.Report != null && device.Report.Id != 0 ? device.Report.Id : 0
                    });
                }

                ViewBag.repDevices = devices.OrderBy(device => device.Manufacturer).ThenBy(device => device.Model).
                                     ThenBy(device => device.Revision).ThenBy(device => device.Bus).ToList();
            }
        }
        catch (Exception)
        {
        #if DEBUG
            throw;
        #endif
            return(Content("Could not read statistics"));
        }

        return(View());
    }
コード例 #4
0
        public ActionResult Index()
        {
            ViewBag.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            try
            {
                if (
                    System.IO.File
                    .Exists(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(),
                                         "Statistics", "Statistics.xml")))
                {
                    try
                    {
                        Stats statistics = new Stats();

                        XmlSerializer xs = new XmlSerializer(statistics.GetType());
                        FileStream    fs =
                            WaitForFile(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Statistics", "Statistics.xml"),
                                        FileMode.Open, FileAccess.Read, FileShare.Read);
                        statistics = (Stats)xs.Deserialize(fs);
                        fs.Close();

                        StatsConverter.Convert(statistics);

                        System.IO.File
                        .Delete(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(),
                                             "Statistics", "Statistics.xml"));
                    }
                    catch (XmlException)
                    {
                        // Do nothing
                    }
                }

                if (ctx.OperatingSystems.Any())
                {
                    operatingSystems = new List <NameValueStats>();
                    foreach (OperatingSystem nvs in ctx.OperatingSystems)
                    {
                        operatingSystems.Add(new NameValueStats
                        {
                            name =
                                $"{DetectOS.GetPlatformName((PlatformID)Enum.Parse(typeof(PlatformID), nvs.Name), nvs.Version)}{(string.IsNullOrEmpty(nvs.Version) ? "" : " ")}{nvs.Version}",
                            Value = nvs.Count
                        });
                    }

                    ViewBag.repOperatingSystems = operatingSystems.OrderBy(os => os.name).ToList();

                    List <PieSeriesData> osPieData = new List <PieSeriesData>();

                    decimal totalOsCount = ctx.OperatingSystems.Sum(o => o.Count);
                    foreach (string os in ctx.OperatingSystems.Select(o => o.Name).Distinct().ToList())
                    {
                        decimal osCount = ctx.OperatingSystems.Where(o => o.Name == os).Sum(o => o.Count);

                        osPieData.Add(new PieSeriesData
                        {
                            Name =
                                DetectOS.GetPlatformName((PlatformID)Enum.Parse(typeof(PlatformID),
                                                                                os)),
                            Y        = (double?)(osCount / totalOsCount),
                            Sliced   = os == "Linux",
                            Selected = os == "Linux"
                        });
                    }

                    ViewData["osPieData"] = osPieData;

                    List <PieSeriesData> linuxPieData = new List <PieSeriesData>();

                    decimal linuxCount = ctx.OperatingSystems.Where(o => o.Name == PlatformID.Linux.ToString())
                                         .Sum(o => o.Count);
                    foreach (OperatingSystem version in
                             ctx.OperatingSystems.Where(o => o.Name == PlatformID.Linux.ToString()))
                    {
                        linuxPieData.Add(new PieSeriesData
                        {
                            Name =
                                $"{DetectOS.GetPlatformName(PlatformID.Linux, version.Version)}{(string.IsNullOrEmpty(version.Version) ? "" : " ")}{version.Version}",
                            Y = (double?)(version.Count / linuxCount)
                        });
                    }

                    ViewData["linuxPieData"] = linuxPieData;

                    List <PieSeriesData> macosPieData = new List <PieSeriesData>();

                    decimal macosCount = ctx.OperatingSystems.Where(o => o.Name == PlatformID.MacOSX.ToString())
                                         .Sum(o => o.Count);
                    foreach (OperatingSystem version in
                             ctx.OperatingSystems.Where(o => o.Name == PlatformID.MacOSX.ToString()))
                    {
                        macosPieData.Add(new PieSeriesData
                        {
                            Name =
                                $"{DetectOS.GetPlatformName(PlatformID.MacOSX, version.Version)}{(string.IsNullOrEmpty(version.Version) ? "" : " ")}{version.Version}",
                            Y = (double?)(version.Count / macosCount)
                        });
                    }

                    ViewData["macosPieData"] = macosPieData;

                    List <PieSeriesData> windowsPieData = new List <PieSeriesData>();

                    decimal windowsCount = ctx.OperatingSystems.Where(o => o.Name == PlatformID.Win32NT.ToString())
                                           .Sum(o => o.Count);
                    foreach (OperatingSystem version in
                             ctx.OperatingSystems.Where(o => o.Name == PlatformID.Win32NT.ToString()))
                    {
                        windowsPieData.Add(new PieSeriesData
                        {
                            Name =
                                $"{DetectOS.GetPlatformName(PlatformID.Win32NT, version.Version)}{(string.IsNullOrEmpty(version.Version) ? "" : " ")}{version.Version}",
                            Y = (double?)(version.Count / windowsCount)
                        });
                    }

                    ViewData["windowsPieData"] = windowsPieData;
                }

                if (ctx.Versions.Any())
                {
                    versions = new List <NameValueStats>();
                    foreach (Version nvs in ctx.Versions)
                    {
                        versions.Add(new NameValueStats
                        {
                            name  = nvs.Value == "previous" ? "Previous than 3.4.99.0" : nvs.Value,
                            Value = nvs.Count
                        });
                    }

                    ViewBag.repVersions = versions.OrderBy(ver => ver.name).ToList();

                    decimal totalVersionCount = ctx.Versions.Sum(o => o.Count);

                    ViewData["versionsPieData"] = ctx.Versions.Select(version => new PieSeriesData
                    {
                        Name =
                            version.Value == "previous"
                                ? "Previous than 3.4.99.0"
                                : version.Value,
                        Y = (double?)(version.Count /
                                      totalVersionCount),
                        Sliced   = version.Value == "previous",
                        Selected = version.Value == "previous"
                    }).ToList();
                }

                if (ctx.Commands.Any())
                {
                    ViewBag.repCommands = ctx.Commands.OrderBy(c => c.Name).ToList();

                    decimal totalCommandCount = ctx.Commands.Sum(o => o.Count);

                    ViewData["commandsPieData"] = ctx
                                                  .Commands.Select(command => new PieSeriesData
                    {
                        Name = command.Name,
                        Y    = (double?)(command.Count /
                                         totalCommandCount),
                        Sliced   = command.Name == "analyze",
                        Selected = command.Name == "analyze"
                    }).ToList();
                }

                if (ctx.Filters.Any())
                {
                    ViewBag.repFilters = ctx.Filters.OrderBy(filter => filter.Name).ToList();

                    List <PieSeriesData> filtersPieData = new List <PieSeriesData>();

                    decimal totalFiltersCount = ctx.Filters.Sum(o => o.Count);
                    foreach (Filter filter in ctx.Filters.ToList())
                    {
                        filtersPieData.Add(new PieSeriesData
                        {
                            Name     = filter.Name,
                            Y        = (double?)(filter.Count / totalFiltersCount),
                            Sliced   = filter.Name == "No filter",
                            Selected = filter.Name == "No filter"
                        });
                    }

                    ViewData["filtersPieData"] = filtersPieData;
                }

                if (ctx.MediaFormats.Any())
                {
                    ViewBag.repMediaImages = ctx.MediaFormats.OrderBy(filter => filter.Name).ToList();

                    List <PieSeriesData> formatsPieData = new List <PieSeriesData>();

                    decimal totalFormatsCount = ctx.MediaFormats.Sum(o => o.Count);
                    decimal top10FormatCount  = 0;

                    foreach (MediaFormat format in ctx.MediaFormats.OrderByDescending(o => o.Count).Take(10))
                    {
                        top10FormatCount += format.Count;

                        formatsPieData.Add(new PieSeriesData
                        {
                            Name = format.Name, Y = (double?)(format.Count / totalFormatsCount)
                        });
                    }

                    formatsPieData.Add(new PieSeriesData
                    {
                        Name = "Other",
                        Y    = (double?)((totalFormatsCount - top10FormatCount) /
                                         totalFormatsCount),
                        Sliced   = true,
                        Selected = true
                    });

                    ViewData["formatsPieData"] = formatsPieData;
                }

                if (ctx.Partitions.Any())
                {
                    ViewBag.repPartitions = ctx.Partitions.OrderBy(filter => filter.Name).ToList();

                    List <PieSeriesData> partitionsPieData = new List <PieSeriesData>();

                    decimal totalPartitionsCount = ctx.Partitions.Sum(o => o.Count);
                    decimal top10PartitionCount  = 0;

                    foreach (Partition partition in ctx.Partitions.OrderByDescending(o => o.Count).Take(10))
                    {
                        top10PartitionCount += partition.Count;

                        partitionsPieData.Add(new PieSeriesData
                        {
                            Name = partition.Name,
                            Y    = (double?)(partition.Count / totalPartitionsCount)
                        });
                    }

                    partitionsPieData.Add(new PieSeriesData
                    {
                        Name = "Other",
                        Y    = (double?)((totalPartitionsCount - top10PartitionCount) /
                                         totalPartitionsCount),
                        Sliced   = true,
                        Selected = true
                    });

                    ViewData["partitionsPieData"] = partitionsPieData;
                }

                if (ctx.Filesystems.Any())
                {
                    ViewBag.repFilesystems = ctx.Filesystems.OrderBy(filter => filter.Name).ToList();

                    List <PieSeriesData> filesystemsPieData = new List <PieSeriesData>();

                    decimal totalFilesystemsCount = ctx.Filesystems.Sum(o => o.Count);
                    decimal top10FilesystemCount  = 0;

                    foreach (Filesystem filesystem in ctx.Filesystems.OrderByDescending(o => o.Count).Take(10))
                    {
                        top10FilesystemCount += filesystem.Count;

                        filesystemsPieData.Add(new PieSeriesData
                        {
                            Name = filesystem.Name,
                            Y    = (double?)(filesystem.Count / totalFilesystemsCount)
                        });
                    }

                    filesystemsPieData.Add(new PieSeriesData
                    {
                        Name = "Other",
                        Y    = (double?)((totalFilesystemsCount - top10FilesystemCount) /
                                         totalFilesystemsCount),
                        Sliced   = true,
                        Selected = true
                    });

                    ViewData["filesystemsPieData"] = filesystemsPieData;
                }

                if (ctx.Medias.Any())
                {
                    realMedia    = new List <MediaItem>();
                    virtualMedia = new List <MediaItem>();
                    foreach (Media nvs in ctx.Medias)
                    {
                        try
                        {
                            MediaType
                            .MediaTypeToString((CommonTypes.MediaType)Enum.Parse(typeof(CommonTypes.MediaType), nvs.Type),
                                               out string type, out string subtype);

                            if (nvs.Real)
                            {
                                realMedia.Add(new MediaItem {
                                    Type = type, SubType = subtype, Count = nvs.Count
                                });
                            }
                            else
                            {
                                virtualMedia.Add(new MediaItem {
                                    Type = type, SubType = subtype, Count = nvs.Count
                                });
                            }
                        }
                        catch
                        {
                            if (nvs.Real)
                            {
                                realMedia.Add(new MediaItem {
                                    Type = nvs.Type, SubType = null, Count = nvs.Count
                                });
                            }
                            else
                            {
                                virtualMedia.Add(new MediaItem {
                                    Type = nvs.Type, SubType = null, Count = nvs.Count
                                });
                            }
                        }
                    }

                    if (realMedia.Count > 0)
                    {
                        ViewBag.repRealMedia =
                            realMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType).ToList();

                        List <PieSeriesData> realMediaPieData = new List <PieSeriesData>();

                        decimal totalRealMediaCount = realMedia.Sum(o => o.Count);
                        decimal top10RealMediaCount = 0;

                        foreach (MediaItem realMediaItem in realMedia.OrderByDescending(o => o.Count).Take(10))
                        {
                            top10RealMediaCount += realMediaItem.Count;

                            realMediaPieData.Add(new PieSeriesData
                            {
                                Name = $"{realMediaItem.Type} ({realMediaItem.SubType})",
                                Y    = (double?)(realMediaItem.Count / totalRealMediaCount)
                            });
                        }

                        realMediaPieData.Add(new PieSeriesData
                        {
                            Name = "Other",
                            Y    = (double?)((totalRealMediaCount - top10RealMediaCount) /
                                             totalRealMediaCount),
                            Sliced   = true,
                            Selected = true
                        });

                        ViewData["realMediaPieData"] = realMediaPieData;
                    }

                    if (virtualMedia.Count > 0)
                    {
                        ViewBag.repVirtualMedia =
                            virtualMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType).ToList();

                        List <PieSeriesData> virtualMediaPieData = new List <PieSeriesData>();

                        decimal totalVirtualMediaCount = virtualMedia.Sum(o => o.Count);
                        decimal top10VirtualMediaCount = 0;

                        foreach (MediaItem virtualMediaItem in virtualMedia.OrderByDescending(o => o.Count).Take(10))
                        {
                            top10VirtualMediaCount += virtualMediaItem.Count;

                            virtualMediaPieData.Add(new PieSeriesData
                            {
                                Name =
                                    $"{virtualMediaItem.Type} ({virtualMediaItem.SubType})",
                                Y = (double?)(virtualMediaItem.Count /
                                              totalVirtualMediaCount)
                            });
                        }

                        virtualMediaPieData.Add(new PieSeriesData
                        {
                            Name = "Other",
                            Y    = (double?)
                                   ((totalVirtualMediaCount - top10VirtualMediaCount) /
                                    totalVirtualMediaCount),
                            Sliced   = true,
                            Selected = true
                        });

                        ViewData["virtualMediaPieData"] = virtualMediaPieData;
                    }
                }

                if (ctx.DeviceStats.Any())
                {
                    devices = new List <DeviceItem>();
                    foreach (DeviceStat device in ctx.DeviceStats.ToList())
                    {
                        string xmlFile;
                        if (!string.IsNullOrWhiteSpace(device.Manufacturer) &&
                            !string.IsNullOrWhiteSpace(device.Model) &&
                            !string.IsNullOrWhiteSpace(device.Revision))
                        {
                            xmlFile = device.Manufacturer + "_" + device.Model + "_" + device.Revision + ".xml";
                        }
                        else if (!string.IsNullOrWhiteSpace(device.Manufacturer) &&
                                 !string.IsNullOrWhiteSpace(device.Model))
                        {
                            xmlFile = device.Manufacturer + "_" + device.Model + ".xml";
                        }
                        else if (!string.IsNullOrWhiteSpace(device.Model) && !string.IsNullOrWhiteSpace(device.Revision))
                        {
                            xmlFile = device.Model + "_" + device.Revision + ".xml";
                        }
                        else
                        {
                            xmlFile = device.Model + ".xml";
                        }

                        xmlFile = xmlFile.Replace('/', '_').Replace('\\', '_').Replace('?', '_');

                        if (System.IO.File.Exists(Path.Combine(HostingEnvironment.MapPath("~"), "Reports", xmlFile)))
                        {
                            DeviceReport deviceReport = new DeviceReport();

                            XmlSerializer xs = new XmlSerializer(deviceReport.GetType());
                            FileStream    fs =
                                WaitForFile(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Reports", xmlFile),
                                            FileMode.Open, FileAccess.Read, FileShare.Read);
                            deviceReport = (DeviceReport)xs.Deserialize(fs);
                            fs.Close();

                            DeviceReportV2 deviceReportV2 = new DeviceReportV2(deviceReport);

                            device.Report = ctx.Devices.Add(new Device(deviceReportV2));
                            ctx.SaveChanges();

                            System.IO.File
                            .Delete(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(),
                                                 "Reports", xmlFile));
                        }

                        devices.Add(new DeviceItem
                        {
                            Manufacturer = device.Manufacturer,
                            Model        = device.Model,
                            Revision     = device.Revision,
                            Bus          = device.Bus,
                            ReportId     = device.Report != null && device.Report.Id != 0
                                           ? device.Report.Id
                                           : 0
                        });
                    }

                    ViewBag.repDevices = devices.OrderBy(device => device.Manufacturer).ThenBy(device => device.Model)
                                         .ThenBy(device => device.Revision).ThenBy(device => device.Bus)
                                         .ToList();

                    ViewData["devicesBusPieData"] = (from deviceBus in devices.Select(d => d.Bus).Distinct()
                                                     let deviceBusCount = devices.Count(d => d.Bus == deviceBus)
                                                                          select new PieSeriesData
                    {
                        Name = deviceBus,
                        Y = deviceBusCount / (double)devices.Count
                    }).ToList();

                    ViewData["devicesManufacturerPieData"] =
                        (from manufacturer in
                         devices.Where(d => d.Manufacturer != null).Select(d => d.Manufacturer.ToLowerInvariant())
                         .Distinct()
                         let manufacturerCount = devices.Count(d => d.Manufacturer?.ToLowerInvariant() == manufacturer)
                                                 select new PieSeriesData {
                        Name = manufacturer, Y = manufacturerCount / (double)devices.Count
                    })
                        .ToList();
                }
            }
            catch (Exception)
            {
                #if DEBUG
                throw;
                #endif
                return(Content("Could not read statistics"));
            }

            return(View());
        }
コード例 #5
0
    public async Task <IActionResult> UploadReport()
    {
        var response = new ContentResult
        {
            StatusCode  = (int)HttpStatusCode.OK,
            ContentType = "text/plain"
        };

        try
        {
            var         newReport = new DeviceReport();
            HttpRequest request   = HttpContext.Request;

            var xs = new XmlSerializer(newReport.GetType());

            newReport =
                (DeviceReport)xs.Deserialize(new StringReader(await new StreamReader(request.Body).ReadToEndAsync()));

            if (newReport == null)
            {
                response.Content = "notstats";

                return(response);
            }

            var reportV2 = new DeviceReportV2(newReport);
            var jsonSw   = new StringWriter();

            await jsonSw.WriteAsync(JsonConvert.SerializeObject(reportV2, Formatting.Indented,
                                                                new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            }));

            string reportV2String = jsonSw.ToString();
            jsonSw.Close();

            var newUploadedReport = new UploadedReport(reportV2);

            // Ensure CHS and CurrentCHS are not duplicates
            if (newUploadedReport.ATA?.ReadCapabilities?.CHS != null &&
                newUploadedReport.ATA?.ReadCapabilities?.CurrentCHS != null)
            {
                if (newUploadedReport.ATA.ReadCapabilities.CHS.Cylinders ==
                    newUploadedReport.ATA.ReadCapabilities.CurrentCHS.Cylinders &&
                    newUploadedReport.ATA.ReadCapabilities.CHS.Heads ==
                    newUploadedReport.ATA.ReadCapabilities.CurrentCHS.Heads &&
                    newUploadedReport.ATA.ReadCapabilities.CHS.Sectors ==
                    newUploadedReport.ATA.ReadCapabilities.CurrentCHS.Sectors)
                {
                    newUploadedReport.ATA.ReadCapabilities.CHS = newUploadedReport.ATA.ReadCapabilities.CurrentCHS;
                }
            }

            // Check if the CHS or CurrentCHS of this report already exist in the database
            if (newUploadedReport.ATA?.ReadCapabilities?.CHS != null)
            {
                Chs existingChs =
                    _ctx.Chs.FirstOrDefault(c => c.Cylinders == newUploadedReport.ATA.ReadCapabilities.CHS.Cylinders &&
                                            c.Heads == newUploadedReport.ATA.ReadCapabilities.CHS.Heads &&
                                            c.Sectors == newUploadedReport.ATA.ReadCapabilities.CHS.Sectors);

                if (existingChs != null)
                {
                    newUploadedReport.ATA.ReadCapabilities.CHS = existingChs;
                }
            }

            if (newUploadedReport.ATA?.ReadCapabilities?.CurrentCHS != null)
            {
                Chs existingChs =
                    _ctx.Chs.FirstOrDefault(c =>
                                            c.Cylinders == newUploadedReport.ATA.ReadCapabilities.CurrentCHS.
                                            Cylinders &&
                                            c.Heads == newUploadedReport.ATA.ReadCapabilities.CurrentCHS.Heads &&
                                            c.Sectors == newUploadedReport.ATA.ReadCapabilities.CurrentCHS.Sectors);

                if (existingChs != null)
                {
                    newUploadedReport.ATA.ReadCapabilities.CurrentCHS = existingChs;
                }
            }

            if (newUploadedReport.ATA?.RemovableMedias != null)
            {
                foreach (TestedMedia media in newUploadedReport.ATA.RemovableMedias)
                {
                    if (media.CHS != null &&
                        media.CurrentCHS != null)
                    {
                        if (media.CHS.Cylinders == media.CurrentCHS.Cylinders &&
                            media.CHS.Heads == media.CurrentCHS.Heads &&
                            media.CHS.Sectors == media.CurrentCHS.Sectors)
                        {
                            media.CHS = media.CurrentCHS;
                        }
                    }

                    if (media.CHS != null)
                    {
                        Chs existingChs =
                            _ctx.Chs.FirstOrDefault(c => c.Cylinders == media.CHS.Cylinders &&
                                                    c.Heads == media.CHS.Heads && c.Sectors == media.CHS.Sectors);

                        if (existingChs != null)
                        {
                            media.CHS = existingChs;
                        }
                    }

                    if (media.CHS != null)
                    {
                        Chs existingChs =
                            _ctx.Chs.FirstOrDefault(c => c.Cylinders == media.CurrentCHS.Cylinders &&
                                                    c.Heads == media.CurrentCHS.Heads &&
                                                    c.Sectors == media.CurrentCHS.Sectors);

                        if (existingChs != null)
                        {
                            media.CurrentCHS = existingChs;
                        }
                    }
                }
            }

            await _ctx.Reports.AddAsync(newUploadedReport);

            await _ctx.SaveChangesAsync();

            var pgpIn  = new MemoryStream(Encoding.UTF8.GetBytes(reportV2String));
            var pgpOut = new MemoryStream();
            var pgp    = new ChoPGPEncryptDecrypt();

            await pgp.EncryptAsync(pgpIn, pgpOut,
                                   Path.Combine(_environment.ContentRootPath ?? throw new InvalidOperationException(),
                                                "public.asc"));

            pgpOut.Position = 0;
            reportV2String  = Encoding.UTF8.GetString(pgpOut.ToArray());

            var message = new MimeMessage
            {
                Subject = "New device report (old version)",
                Body    = new TextPart("plain")
                {
                    Text = reportV2String
                }
            };

            message.From.Add(new MailboxAddress("Aaru Server", "*****@*****.**"));
            message.To.Add(new MailboxAddress("Natalia Portillo", "*****@*****.**"));

            using (var client = new SmtpClient())
            {
                await client.ConnectAsync("mail.claunia.com", 25, false);

                await client.SendAsync(message);

                await client.DisconnectAsync(true);
            }

            response.Content = "ok";

            return(response);
        }

        // ReSharper disable once RedundantCatchClause
        catch
        {
        #if DEBUG
            if (Debugger.IsAttached)
            {
                throw;
            }
        #endif
            response.Content = "error";

            return(response);
        }
    }
コード例 #6
0
        public async Task <IActionResult> UploadReport()
        {
            var response = new ContentResult
            {
                StatusCode = (int)HttpStatusCode.OK, ContentType = "text/plain"
            };

            try
            {
                var         newReport = new DeviceReport();
                HttpRequest request   = HttpContext.Request;

                var xs = new XmlSerializer(newReport.GetType());

                newReport =
                    (DeviceReport)
                    xs.Deserialize(new StringReader(await new StreamReader(request.Body).ReadToEndAsync()));

                if (newReport == null)
                {
                    response.Content = "notstats";

                    return(response);
                }

                var reportV2 = new DeviceReportV2(newReport);
                var jsonSw   = new StringWriter();

                jsonSw.Write(JsonConvert.SerializeObject(reportV2, Formatting.Indented, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));

                string reportV2String = jsonSw.ToString();
                jsonSw.Close();

                ctx.Reports.Add(new UploadedReport(reportV2));
                ctx.SaveChanges();

                var pgpIn  = new MemoryStream(Encoding.UTF8.GetBytes(reportV2String));
                var pgpOut = new MemoryStream();
                var pgp    = new ChoPGPEncryptDecrypt();

                pgp.Encrypt(pgpIn, pgpOut,
                            Path.Combine(_environment.ContentRootPath ?? throw new InvalidOperationException(),
                                         "public.asc"));

                pgpOut.Position = 0;
                reportV2String  = Encoding.UTF8.GetString(pgpOut.ToArray());

                var message = new MimeMessage
                {
                    Subject = "New device report (old version)", Body = new TextPart("plain")
                    {
                        Text = reportV2String
                    }
                };

                message.From.Add(new MailboxAddress("DiscImageChef", "*****@*****.**"));
                message.To.Add(new MailboxAddress("Natalia Portillo", "*****@*****.**"));

                using (var client = new SmtpClient())
                {
                    client.Connect("mail.claunia.com", 25, false);
                    client.Send(message);
                    client.Disconnect(true);
                }

                response.Content = "ok";

                return(response);
            }

            // ReSharper disable once RedundantCatchClause
            catch
            {
            #if DEBUG
                if (Debugger.IsAttached)
                {
                    throw;
                }
            #endif
                response.Content = "error";

                return(response);
            }
        }
コード例 #7
0
        public HttpResponseMessage UploadReport()
        {
            HttpResponseMessage response = new HttpResponseMessage {
                StatusCode = HttpStatusCode.OK
            };

            try
            {
                DeviceReport newReport = new DeviceReport();
                HttpRequest  request   = HttpContext.Current.Request;

                XmlSerializer xs = new XmlSerializer(newReport.GetType());
                newReport = (DeviceReport)xs.Deserialize(request.InputStream);

                if (newReport == null)
                {
                    response.Content = new StringContent("notstats", Encoding.UTF8, "text/plain");
                    return(response);
                }

                DeviceReportV2 reportV2 = new DeviceReportV2(newReport);
                StringWriter   jsonSw   = new StringWriter();
                jsonSw.Write(JsonConvert.SerializeObject(reportV2, Formatting.Indented,
                                                         new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
                string reportV2String = jsonSw.ToString();
                jsonSw.Close();

                ctx.Reports.Add(new UploadedReport(reportV2));
                ctx.SaveChanges();

                MemoryStream         pgpIn  = new MemoryStream(Encoding.UTF8.GetBytes(reportV2String));
                MemoryStream         pgpOut = new MemoryStream();
                ChoPGPEncryptDecrypt pgp    = new ChoPGPEncryptDecrypt();
                pgp.Encrypt(pgpIn, pgpOut,
                            Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(),
                                         "public.asc"), true);
                pgpOut.Position = 0;
                reportV2String  = Encoding.UTF8.GetString(pgpOut.ToArray());

                MimeMessage message = new MimeMessage
                {
                    Subject = "New device report (old version)",
                    Body    = new TextPart("plain")
                    {
                        Text = reportV2String
                    }
                };
                message.From.Add(new MailboxAddress("DiscImageChef", "*****@*****.**"));
                message.To.Add(new MailboxAddress("Natalia Portillo", "*****@*****.**"));

                using (SmtpClient client = new SmtpClient())
                {
                    client.Connect("mail.claunia.com", 25, false);
                    client.Send(message);
                    client.Disconnect(true);
                }

                response.Content = new StringContent("ok", Encoding.UTF8, "text/plain");
                return(response);
            }
            // ReSharper disable once RedundantCatchClause
            catch
            {
                #if DEBUG
                if (Debugger.IsAttached)
                {
                    throw;
                }
                #endif
                response.Content = new StringContent("error", Encoding.UTF8, "text/plain");
                return(response);
            }
        }