Beispiel #1
0
        /// <summary>
        /// Get a lists of content that are set to be included in scanning
        /// </summary>
        /// <returns>List of show that are included in scanning</returns>
        public List <Content> GetScannableContent(bool updateMissing, ScanType scanType)
        {
            List <Content> includeShow = new List <Content>();

            for (int i = 0; i < this.Count; i++)
            {
                bool include = true;
                switch (scanType)
                {
                case ScanType.TvMissing:
                    include = (this[i] as TvShow).DoMissingCheck;
                    break;

                case ScanType.TvRename:
                case ScanType.TvFolder:
                case ScanType.MovieFolder:
                    include = this[i].DoRenaming;
                    break;
                }

                if (include && !string.IsNullOrEmpty(this[i].DatabaseName))
                {
                    if (updateMissing)
                    {
                        this[i].UpdateMissing();
                    }
                    includeShow.Add(this[i]);
                }
            }
            return(includeShow);
        }
Beispiel #2
0
        private static Post ProcessPost(string html, ScanType scanType)
        {
            var          title = scanType == ScanType.Keyword ? "<font size=2 face=arial> - " : "<font size=2 face=arial COLOR=\"#0000FF\">";
            const string END   = "</font>";

            var index = 0;
            var post  = new Post
            {
                IsNew       = html[0] == '2',
                Category    = Utils.GetValue(html, "<font size=2 face=arial color=0000FF>", END, ref index, false),
                Title       = Utils.GetValue(html, title, END, ref index),
                HasImage    = html.IndexOf("camera_icon.gif", index, StringComparison.Ordinal) > 0,
                Description = Utils.HighlightPrices(Utils.GetValue(html, "<DD><font size=2 face=arial>", END, ref index)),
                Id          = int.Parse(Utils.GetValue(html, "<DD><font size=1 face=arial>Listing #", " -  ", ref index)),
                SubmittedOn = DateTime.Parse(Utils.GetValue(html, "Submitted on ", " by ", ref index)),
                CallSign    = GetCallSign(html, ref index)
            };

            if (post.Title.StartsWith("WTB ", true, null) || post.Title.StartsWith("WTB:", true, null) || post.Title.StartsWith("WTB-", true, null))
            {
                return(null);
            }

            DateTime.TryParse(Utils.GetValue(html, "Modified on ", " - IP:", ref index, false), out var dt);
            post.ModifiedOn = dt == DateTime.MinValue ? (DateTime?)null : dt;

            post.Price = Utils.GetPrice(post);
            if (!string.IsNullOrEmpty(post.Category))
            {
                post.Category = post.Category.ToLower();
            }

            return(post);
        }
Beispiel #3
0
        private async Task ScanBatch(List <CompetitorData> competitors, ScanType scanType)
        {
            try
            {
                var tasks = new List <Task>();
                foreach (var competitor in competitors)
                {
                    var currentCompetition = scanType == ScanType.DailyGames && competitor.NextScan != null
                        ? competitor.NextScan.CompetitionData : competitor.CompetitionData;

                    var task = ScanSingleCompetitor(competitor, scanType)
                               .ContinueWith(t => HandleCompetitorScan(competitor, scanType, t.Result));
                    tasks.Add(task);
                }

                if (tasks.Count > 0)
                {
                    var tasksToWaitFor = tasks.ToArray();
                    tasks.Clear();

                    await Task.WhenAll(tasksToWaitFor);
                }
            }
            catch (Exception exception)
            {
            }
        }
        private Entry CreateScanEntryFor(JObject o, DateTime timestamp, Event @event)
        {
            string   scanTypeText = o["ScanType"].Value <string>();
            ScanType scanType     = ScanType.Unknown;

            if (!Enum.TryParse <ScanType>(scanTypeText, out scanType))
            {
                log.Error($"Could not detect scan type for {scanTypeText}");
                scanType = ScanType.Unknown;
            }
            // check if we have an AutoScan with detailed data
            bool hasDetailData   = false;
            var  checkPlanetData = o["PlanetClass"];

            if (checkPlanetData != null)
            {
                string planetClass = checkPlanetData.Value <string>();
                if (!String.IsNullOrWhiteSpace(planetClass))
                {
                    hasDetailData = true;
                }
            }

            if ((scanType == ScanType.AutoScan) && (!hasDetailData))
            {
                return(o.ToObject <EntryScanAutoScan>());
            }
            else if ((scanType == ScanType.Detailed) || (hasDetailData))
            {
                return(o.ToObject <EntryScanDetailed>());
            }
            return(new Entry(timestamp, @event));
        }
Beispiel #5
0
        // handler for scan result
        private void HandlerScanResult(
            IMacMgmtSap sender,
            MacEnum status,
            ScanType scanType,
            Byte channelPage,
            UInt32 unscannedChannel,
            byte[] energyDetectList,
            PanDescriptor[] panDescriptorList)
        {
            // store networks
            if (panDescriptorList != null)
            {
                lock (_scanResults)
                {
                    int length = panDescriptorList.Length;
                    for (int i = 0; i < length; i++)
                    {
                        ScanResultInternal res = new ScanResultInternal();
                        res.panDescriptor  = panDescriptorList[i];
                        res.isMeshProtocol = false;
                        _scanResults.Add(res);
                    }
                }
            }

            ScanNextPage();
        }
Beispiel #6
0
        private TreeNode AddFileToTree(ScanType scanType, FileInfo fileInfo, string fullname)
        {
            TreeNode newNode;

            switch (scanType)
            {
            case ScanType.Disk:
                newNode = parent.AddDiskToTree(fileInfo, fullname);
                break;

            case ScanType.Tape:
                newNode = parent.AddTapeToTree(fileInfo, fullname);
                break;

            case ScanType.ROM:
                newNode = parent.AddRomToTree(fileInfo, fullname);
                break;

            default:
                newNode = parent.AddOtherFileToTree(fileInfo, fullname);
                break;
            }

            return(newNode);
        }
Beispiel #7
0
 public void OnDialogClose(ScanType scanType, CallbackHandler callback)
 {
     if (DialogClose != null)
     {
         DialogClose(this, new ScanEventArgs(scanType, callback));
     }
 }
Beispiel #8
0
        private static Post ProcessPost(string html, ScanType scanType)
        {
            var index = 0;

            var post = new Post
            {
                IsNew       = true,
                Id          = int.Parse(Utils.GetValue(html, $"href=\"/classifieds/", "\"", ref index)),
                Title       = Utils.GetValue(html, ">", "</a>", ref index),
                SubmittedOn = DateTime.Parse(Utils.GetValue(html, "User IP</th>\n\t\t</tr><tr><td>", scanType == ScanType.Keyword ? "</td>" : "<", ref index)),
                //CallSign = Utils.GetValue(html, "profile/", "\"", ref index),
                Category    = Utils.GetValue(html, "\">", "</a>", ref index),
                HasImage    = html.IndexOf("<img alt style", index, StringComparison.Ordinal) < 0 && html.IndexOf(";base64,TUNRS1", index, StringComparison.Ordinal) < 0,
                Description = Utils.HighlightPrices(Utils.GetValue(html, "float:right\">", "</div>", ref index)),
            };

            if (post.Title.StartsWith("WTB ", true, null) || post.Title.StartsWith("WTB:", true, null) || post.Title.StartsWith("WTB-", true, null))
            {
                return(null);
            }

            post.Price = Utils.GetPrice(post);
            if (!string.IsNullOrEmpty(post.Category))
            {
                post.Category = post.Category.ToLower();
            }

            return(post);
        }
Beispiel #9
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     if (this.bodyFrameReader != null)
     {
         this.bodyFrameReader.Dispose();
         this.bodyFrameReader = null;
     }
     if (this.kinectSensor != null)
     {
         this.kinectSensor.Close();
         this.kinectSensor = null;
     }
     this.coordinateMapper = null;
     this.displayWidth     = 0;
     this.displayHeight    = 0;
     this.bodyFrameReader  = null;
     this.bones            = null;
     this.bodyColors       = null;
     this.drawingGroup     = null;
     this.imageSource      = null;
     this.DataContext      = null;
     this.scanType         = ScanType.Arm;
     init();
     this.bodyFrameReader.FrameArrived += this.Reader_FrameArrived;
 }
        public static bool RecordScan(int deviceId, ScanType scanType, DateTime scanStartTime)
        {
            Transaction transaction = new Transaction(IsolationLevel.RepeatableRead, "ScanHistoryUpdate");

            try
            {
                DeviceEntity device = new DeviceEntity();
                transaction.Add(device);
                device.FetchUsingPK(deviceId);

                device.ScansUsed      = device.ScansUsed + 1;
                device.ScansAvailable = device.ScansAvailable - 1;

                ScanHistoryEntity history = device.ScanHistories.AddNew();
                history.ScanType      = scanType;
                history.ScanStartTime = scanStartTime;

                device.Save(true);                              // recurse=true; will also save the history record

                transaction.Commit();

                return(true);
            }
            catch (Exception)
            {
                transaction.Rollback();
                return(false);
            }
            finally
            {
                transaction.Dispose();
            }
        }
Beispiel #11
0
 private void ScanJoystickAxis()
 {
     if (!string.IsNullOrEmpty(_cancelScanButton) &&
         GetButtonDown(_cancelScanButton) || _scanTimeout <= 0.0f)
     {
         StopScan();
     }
     else
     {
         int scanStart = _joystickToScan * AxisConfiguration.MaxJoystickAxes;
         for (int i = 0; i < AxisConfiguration.MaxJoystickAxes; i++)
         {
             if (Mathf.Abs(Input.GetAxisRaw(_rawJoystickAxes[scanStart + i])) >= 1.0f)
             {
                 if (_axisScanHandler(i, _optionalParameters))
                 {
                     _axisScanHandler = null;
                     _scanTimeout     = 0.0f;
                     _scanType        = ScanType.None;
                     break;
                 }
             }
         }
     }
 }
Beispiel #12
0
        /// <summary>
        ///     Build an nmap context with the specified options
        /// </summary>
        /// <param name="scanType">The desired type of scan to perform</param>
        /// <param name="ports">The ports to scan (null of empty for default ports)</param>
        /// <returns>An nmap context for performing the desired scan</returns>
        private NmapContext _portScanCommon(ScanType scanType, string ports)
        {
            NmapContext ctx = GetContext();

            // We always try to detect the OS and the service versions
            ctx.Options.AddAll(new[]
            {
                NmapFlag.ServiceVersion,
                NmapFlag.OsDetection
            });

            // Add the appropriate flag if we're not performing a default scan
            if (scanType != ScanType.Default)
            {
                ctx.Options.Add(_scanTypeToNmapFlag[scanType]);
            }

            // Unless we specify UDP only, then perform a UDP scan in the same run
            if (scanType != ScanType.Default && scanType != ScanType.Udp)
            {
                ctx.Options.Add(NmapFlag.UdpScan);
            }

            // If we have a port specification, then use it
            if (!string.IsNullOrEmpty(ports))
            {
                ctx.Options.Add(NmapFlag.PortSpecification, ports);
            }

            return(ctx);
        }
Beispiel #13
0
        private bool TryParseScanType(string input, ref ScanType scanType)
        {
            switch (input.ToUpperInvariant())
            {
            case "V":
            case "VERTICAL":
                scanType = ScanType.Vertical;
                break;

            case "H":
            case "HORIZONTAL":
                scanType = ScanType.Horizontal;
                break;

            case "S":
            case "STROBE":
                scanType = ScanType.Strobe;
                break;

            case "N":
            case "NOTSCAN":
                scanType = ScanType.NotScan;
                break;

            default:
                Console.WriteLine("Invalid scan type. Use (V, H, S, or N)");
                return(false);
            }

            return(true);
        }
 public ScanTypeModeView(bool IsUse, string data, ScanType type, PropertyChangedEventHandler propertyChangedEventHandler)
 {
     m_bIsUse         = IsUse;
     m_strData        = data;
     m_Type           = type;
     PropertyChanged += propertyChangedEventHandler;
 }
Beispiel #15
0
 public EntryScanAutoScan(DateTime timestamp, Event @event, ScanType scanType, string bodyName, long bodyID, IEnumerable <DynamicBodyIdentifier> parents,
                          double distanceFromArrivalLS, bool wasDiscovered, bool wasMapped, string starType, int?subclass, double?stellarMass, double?absoluteMagnitude, int?age_MY,
                          double?surfaceTemperature, string luminosity, double?semiMajorAxis, double?eccentricity, double?orbitalInclination, double?periapsis, double?orbitalPeriod,
                          double?rotationPeriod, double?axialTilt, double?radius, IEnumerable <Ring> rings)
     : base(timestamp, @event)
 {
     ScanType = scanType;
     BodyName = bodyName;
     BodyID   = bodyID;
     Parents  = parents.ToImmutableArrayOrEmpty();
     DistanceFromArrivalLS = distanceFromArrivalLS;
     WasDiscovered         = wasDiscovered;
     WasMapped             = wasMapped;
     StarType           = starType;
     Subclass           = subclass;
     StellarMass        = stellarMass;
     AbsoluteMagnitude  = absoluteMagnitude;
     Age_MY             = age_MY;
     SurfaceTemperature = surfaceTemperature;
     Luminosity         = luminosity;
     SemiMajorAxis      = semiMajorAxis;
     Eccentricity       = eccentricity;
     OrbitalInclination = orbitalInclination;
     Periapsis          = periapsis;
     OrbitalPeriod      = orbitalPeriod;
     RotationPeriod     = rotationPeriod;
     AxialTilt          = axialTilt;
     Radius             = radius;
     Rings = rings.ToImmutableArrayOrEmpty();
 }
Beispiel #16
0
        /// <summary>
        ///     Perform a TCP port scan on the specified ports with service detection and OS detection.
        /// </summary>
        /// <param name="scanType">The type of scan to perform</param>
        /// <param name="ports">A list of ports to scan</param>
        /// <returns>A ScanResult object detailing the results of the port scan</returns>
        public ScanResult PortScan(ScanType scanType, IEnumerable <int> ports)
        {
            NmapContext ctx = _portScanCommon(scanType,
                                              string.Join(",",
                                                          ports.Select(x => x.ToString(CultureInfo.InvariantCulture))));

            return(new ScanResult(ctx.Run()));
        }
Beispiel #17
0
        /// <summary>
        ///     Perform a TCP port scan on the specified ports with service detection and OS detection.
        /// </summary>
        /// <param name="ScanType">The type of scan to perform</param>
        /// <param name="Ports">A list of ports to scan</param>
        /// <returns>A NMapRun object detailing the results of the port scan</returns>
        public NMapResult PortScan(ScanType ScanType, IEnumerable <int> Ports)
        {
            var NmapContext = _portScanCommon(ScanType,
                                              string.Join(",",
                                                          Ports.Select(X => X.ToString(CultureInfo.InvariantCulture))));

            return(NmapContext.Run());
        }
 public frmFavoriteName(string key, string data, ScanType type)
 {
     InitializeComponent();
     Key  = key;
     Data = data;
     Type = type;
     txtFavoriteName.Text = Key;
 }
        protected override void StartScan()
        {
            base.StartScan();

            if (ConnectionManagerMode == Mode.Scan)
            {
                _scanType = ScanType.None;
            }
        }
Beispiel #20
0
        public Finder(ScanType scanType, FileCompareType fileCompareType, bool includeSubDirectories, string searchPattern = "*")
        {
            var scanOptions = new ScanOptions();
            scanOptions.FileCompareType = fileCompareType;
            scanOptions.IncludeSubDirectories = includeSubDirectories;
            scanOptions.SearchPattern = searchPattern;

            var scannerFactory = new ScannerFactory();
            _scanner = scannerFactory.Create(scanType, scanOptions);
        }
        protected override void StartScan()
        {
            base.StartScan();

            if (ConnectionManagerMode == Mode.Scan)
            {
                UpdateAvailablePorts();
                _scanType = ScanType.None;
            }
        }
Beispiel #22
0
        //public ZebraScanner(T appContext)
        //{
        //    m_AppContext = appContext ?? throw new ArgumentNullException("Param: appContext can't be null!");
        //    SubscribeScanner();
        //}


        public ZebraScanner(T appContext, ScanType scanType, int appUser = 1, int scannerId = 1, int serviceId = 1)
        {
            m_AppContext = appContext ?? throw new ArgumentNullException("Param: appContext can't be null!");
            Database     = new Repository <ScanData>();
            UserId       = appUser;
            ScanType     = scanType;
            ScannerId    = scannerId;
            ServiceId    = serviceId;

            SubscribeScanner();
        }
 protected Scan(double x0, double y0, double width, double height, double dx, double dwelltime_in_ms,
                ScanType type = ScanType.Ramp, double samplingFrequency = 5000)
 {
     X0                = x0;
     Y0                = y0;
     Width             = width;
     Height            = height;
     Dx                = dx;
     DwellTime         = dwelltime_in_ms;
     Type              = type;
     SamplingFrequency = samplingFrequency;
 }
Beispiel #24
0
 public ScanDrive(ScanType scanType, Action completionAction, bool failFirst, int speedOption, string deviceId)
 {
     this.scanType    = scanType;
     this.failFirst   = failFirst;
     this.speedOption = speedOption;
     this.deviceId    = deviceId;
     cancelTokenSrc   = new CancellationTokenSource();
     cancelTokenSrc.Token.Register(completionAction);
     lastTimeRemaining = new CircularList <long>(AVERAGE_BUFFER_SIZE);
     lastTimeRemaining.SetAll(0);
     lastSpeedInMBytesPerSec = new CircularList <double>(AVERAGE_BUFFER_SIZE);
     lastSpeedInMBytesPerSec.SetAll(0);
 }
Beispiel #25
0
        public static void WriteJson(this ScanType value, Utf8JsonWriter writer)
        {
            switch (value)
            {
            case ScanType.Empty: JsonSerializer.Serialize(writer, ""); break;

            case ScanType.Interlaced: JsonSerializer.Serialize(writer, "Interlaced"); break;

            case ScanType.Mbaff: JsonSerializer.Serialize(writer, "MBAFF"); break;

            case ScanType.Progressive: JsonSerializer.Serialize(writer, "Progressive"); break;
            }
        }
Beispiel #26
0
 private async Task RunLoop(TimeSpan timeInterval, ScanType type = ScanType.All)
 {
     while (_isRunning)
     {
         try
         {
             await Task.WhenAll(Task.Delay(timeInterval), Scan(type));
         }
         catch (Exception ex)
         {
         }
     }
 }
Beispiel #27
0
 public void StartScan(ScanType currentScanType, CallbackHandler callback)
 {
     this.currentScanType = currentScanType;
     this.callback        = callback;
     if (!msgfilter)
     {
         this.Enabled = false;
         msgfilter    = true;
         Application.AddMessageFilter(this);
     }
     tw.Init(this.Handle);
     tw.Acquire();
 }
Beispiel #28
0
        /// <summary>
        /// 加载 ListView 数据
        /// </summary>
        public void InitListView()
        {
            try
            {
                this.lvMaterial.Items.Clear();
                this.lblProductCode.Text = this.productModel.ProductCode;
                this.lblTitle.Text       = "返修-" + this.productModel.ProductName;
                this.scantype            = ScanType.MATERIALCODE;
                //获取BOM表的信息

                /**
                 * 一次获取当前产品所有BOM信息
                 * 2014.11.30 By xudy
                 */
                string    sql   = string.Format("SELECT p.*,m.fieldname FROM `productbominfo` p INNER JOIN materialfield m ON p.materialcode=m.materialcode WHERE producttype='{0}' AND productcode='{1}' AND tracetype IN({2})", BaseVariable.DeviceEntity.ProductType, this.productModel.ProductCode, "'扫描追溯','批次追溯'");
                DataTable table = LocalDbDAL.GetDataTable(sql);
                if (table != null && table.Rows.Count > 0)
                {
                    int index = 0;
                    foreach (DataRow row in table.Rows)
                    {
                        ListViewItem item = new ListViewItem(row["materialcode"].ToString()); //材料条码:0
                        item.SubItems.Add(row["materialname"].ToString());                    //:1
                        item.SubItems.Add("");                                                //:2
                        item.SubItems.Add(row["featurecode"].ToString());                     //特征码:3
                        item.SubItems.Add(row["featureindex"].ToString());                    //特征位:4
                        item.SubItems.Add(row["fieldname"].ToString());                       //字段民称:5
                        item.SubItems.Add(row["tracetype"].ToString());                       //追溯类型:6
                        if (index % 2 == 0)
                        {
                            item.BackColor = Color.Gainsboro;//偶数背景色淡灰色
                        }
                        else
                        {
                            item.BackColor = Color.Silver; //奇数背景色为银色
                        }
                        item.ForeColor = Color.Black;      //字体颜色为黑色
                        this.lvMaterial.Items.Add(item);
                        index++;
                    }
                }
                else
                {
                    this.lblTip.Text = "当前型号没有追溯零件";
                }
            }
            catch (Exception ex)
            {
                CLog.WriteErrLog(ex.Message);
            }
        }
        private async Task UpdateLogs(Wallet wallet, Organisation organisation, ScanType scanType)
        {
            var newCount = new OrganisationAccessLog()
            {
                Wallet       = wallet,
                Organisation = organisation,
                CreatedAt    = DateTime.UtcNow,
                ScanType     = scanType
            };

            await _organisationAccessLogRepository.AddAsync(newCount);

            await _organisationAccessLogRepository.SaveAsync();
        }
Beispiel #30
0
 public void OnImagesReceived(List <Bitmap> bitmaps, ScanType scanType, CallbackHandler callback)
 {
     try
     {
         if (ImagesReceived != null)
         {
             ImagesReceived(this, new ScanEventArgs(bitmaps, scanType, callback));
         }
     }
     catch (Exception ex)
     {
         Tiff.LibTiffHelper.WriteToLog(ex);
     }
 }
        // Perform scan to find connected systems
        protected override void DoWorkScan()
        {
            // First try if currentConnection is open or can be opened
            var activeConnection = false;

            switch (_scanType)
            {
            case ScanType.None:
                try
                {
                    activeConnection = TryConnection() == DeviceStatus.Available;
                }
                catch
                {
                    // Do nothing
                }
                _scanType = ScanType.Quick;
                break;

            case ScanType.Quick:
                try
                {
                    activeConnection = QuickScan();
                }
                catch
                {
                    // Do nothing
                }
                _scanType = ScanType.Thorough;
                break;

            case ScanType.Thorough:
                try
                {
                    activeConnection = ThoroughScan();
                }
                catch
                {
                    // Do nothing
                }
                _scanType = ScanType.Quick;
                break;
            }

            // Trigger event when a connection was made
            if (activeConnection)
            {
                ConnectionFoundEvent();
            }
        }
        public Scanner Create(ScanType scanType, ScanOptions scanOptions)
        {
            switch (scanType)
            {
                case ScanType.Simple:
                    return new SimpleScanner(scanOptions);

                case ScanType.Smart:
                    return new SmartScanner(scanOptions);

                default:
                    return null;
            }
        }
 /// <summary>
 /// 保存扫描记录
 /// </summary>
 /// <param name="openId">微信用户OpenId</param>
 /// <param name="sceneId">扫描的二维码的参数</param>
 /// <param name="scanType">扫描类型</param>
 public void SaveScan(string openId, int sceneId, ScanType scanType)
 {
     //微信公众平台要求微信公众号服务器必须在5秒内返回相应结果,否则会重新发送请求,一共重试三次
     //为了避免微信公众号服务器重复接收到同一条扫描记录,造成数据重复,导致统计失真,这里将保存扫描记录的操作放到线程池中异步执行,尽快返回相应结果给微信服务器
     ThreadPool.QueueUserWorkItem(e =>
     {
         int channelId = new ChannelBll().GetChannelIdBySceneId(sceneId);
         if (channelId <= 0)
         {
             return;
         }
         ChannelScanEntity entity = new ChannelScanEntity()
         {
             ChannelId = channelId,
             ScanTime = DateTime.Now,
             OpenId = openId,
             ScanType = scanType
         };
         new ChannelScanDll().AddEntity(entity.GetDataEntity(entity));
     });
 }
Beispiel #34
0
        private ScanType _scanType; // What type of video is this

        private void ResetParameters()
        {
            _error = false;
            _videoCodec = "";
            _audioCodec = "";
            _audioDelay = 0;
            _audioChannels = 0;
            _fps = 0;
            _height = 0;
            _width = 0;
            _duration = 0;
            _cropHeight = 0;
            _cropWidth = 0;
            _cropString = "";
            _audioStream = -1; // Stream number of the selected Audio Channel
            _audioTrack = -1; // Audio track number of the selected Audio Channel (0 based reference, i.e. 0 indicates 1st audio)
            _videoStream = -1; // Stream number for the video stream (there is only 1 video stream per file)
            _videoPID = -1; // Video stream PID
            _audioPID = -1; // Audio stream PID
            _audioLanguage = ""; // Store the language we are selecting
            _selectedAudioImpaired = false; // no imparied audio
            _scanType = ScanType.Unknown; // Do not know the scan type yet
        }
Beispiel #35
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     if (this.bodyFrameReader != null){
         this.bodyFrameReader.Dispose();
         this.bodyFrameReader = null;
     }
     if (this.kinectSensor != null){
         this.kinectSensor.Close();
         this.kinectSensor = null;
     }
     this.coordinateMapper = null;
     this.displayWidth = 0;
     this.displayHeight = 0;
     this.bodyFrameReader = null;
     this.bones = null;
     this.bodyColors = null;
     this.drawingGroup = null;
     this.imageSource = null;
     this.DataContext = null;
     this.scanType = ScanType.Arm;
     init();
     this.bodyFrameReader.FrameArrived += this.Reader_FrameArrived;
 }
Beispiel #36
0
        /// <summary>
        /// Initiates a scan.
        /// </summary>
        /// <param name="type">
        /// The type of scan to start.
        /// </param>
        /// <param name="scanEvent">
        /// The event for which this scan is taking place.
        /// </param>
        /// <returns>
        /// True if a scan was started, false if the requested scan for the given event
        /// has already completed.
        /// </returns>
        public async Task<InitiateScanResult> InitiateScanAsync(ScanType type, Event scanEvent)
        {
            string scanTaskId = GetScanTaskId(type, scanEvent);
            string scanTaskParamString = GetScanTaskParamString(type, scanEvent);
            string scanTaskType = GetScanTaskType();
            int scanTaskPriority = GetScanTaskPriority(type);

            Log.TraceInformation("Initiating Scan, id={0}, type={1}, priority={2}, paramString={3}", scanTaskId, scanTaskType, scanTaskPriority, scanTaskParamString);

            try
            {
                IDistributedTaskParticipationHandle handle = await _taskManager.JoinOrBeginAsync(scanTaskId, scanTaskType, scanTaskPriority, scanTaskParamString, _workerId + "-initiator-" + type.ToString()).ConfigureAwait(false);

                // We immediately leave after starting the task.  This component isn't responsible
                // for participating in scans, all we need to do is initiate them.  ScanMonitors will
                // pick this up and begin working.
                await handle.LeaveAsync(ParticipantState.Departed).ConfigureAwait(false);
                return handle.WasTaskStarted ? InitiateScanResult.ScanWasStarted : InitiateScanResult.ScanWasAlreadyRunning;
            }
            catch (TaskIsOverException)
            {
                Log.TraceInformation("Scan has already ended");

                // This worker just popped up during a time when a scan is needed.  However,
                // the scan was already completed by other workers.  It's tempting to assert here
                // that this isn't an official run, but the problem is we could technically start
                // just moments before the run finished and hit this condition anyway.
                return InitiateScanResult.ScanWasAlreadyComplete;
            }
        }
Beispiel #37
0
 /// <summary>
 ///     Perform a TCP port scan on the specified ports with service detection and OS detection.
 /// </summary>
 /// <param name="scanType">The type of scan to perform</param>
 /// <param name="ports">A list of ports to scan</param>
 /// <returns>A ScanResult object detailing the results of the port scan</returns>
 public ScanResult PortScan(ScanType scanType, IEnumerable<int> ports)
 {
     NmapContext ctx = _portScanCommon(scanType,
                                       string.Join(",",
                                                   ports.Select(x => x.ToString(CultureInfo.InvariantCulture))));
     return new ScanResult(ctx.Run());
 }
Beispiel #38
0
 /// <summary>
 ///     Perform the desired scan with service detection and OS detection.
 /// </summary>
 /// <returns>A ScanResult object detailing the results of the port scan</returns>
 public ScanResult PortScan(ScanType scanType)
 {
     NmapContext ctx = _portScanCommon(scanType, null);
     return new ScanResult(ctx.Run());
 }
Beispiel #39
0
        // handler for scan result
        private void HandlerScanResult(
            IMacMgmtSap sender,
            MacEnum status,
            ScanType scanType,
            Byte channelPage,
            UInt32 unscannedChannel,
            byte[] energyDetectList,
            PanDescriptor[] panDescriptorList)
        {
            // store networks
            if (panDescriptorList != null)
            {
                lock (_scanResults)
                {
                    int length = panDescriptorList.Length;
                    for (int i = 0; i < length; i++)
                    {
                        ScanResultInternal res = new ScanResultInternal();
                        res.panDescriptor = panDescriptorList[i];
                        res.isMeshProtocol = false;
                        _scanResults.Add(res);
                    }
                }
            }

            ScanNextPage();
        }
Beispiel #40
0
        /// <summary>
        /// Updates the Video file properties structure, check for crop, audio and video information
        /// </summary>
        /// <param name="skipCropDetect">True to skip detecting cropping parameters</param>
        /// <param name="detectInterlace">Extracts the video intelacing type by analyzing it in depth</param>
        /// <param name="videoFileName">Path to Original Source Video</param>
        /// <param name="remuxedFileName">Path to Remuxed video, else null or empty string</param>
        /// <param name="edlFile">Path to EDL file else null or empty string</param>
        /// <param name="audioLanguage">Audio Language</param>
        /// <param name="jobStatus">JobStatus</param>
        /// <param name="jobLog">JobLog</param>
        public void UpdateVideoInfo(bool skipCropDetect, bool detectInterlace, string videoFileName, string remuxedFileName, string edlFile, string audioLanguage, JobStatus jobStatus, Log jobLog)
        {
            ResetParameters(); // Reset VideoInfo parameters

            _jobStatus = jobStatus;
            _jobLog = jobLog;
            _EDLFile = edlFile;
            _requestedAudioLanguage = audioLanguage;
            _originalFileName = videoFileName;
            _remuxedFileName = remuxedFileName;

            Ini ini = new Ini(GlobalDefs.ProfileFile);

            _skipCropDetect = skipCropDetect;
            _detectInterlacing = detectInterlace;

            _jobLog.WriteEntry(this, "Reading MediaInfo from " + SourceVideo, Log.LogEntryType.Information);

            _videoCodec = VideoParams.VideoFormat(SourceVideo);
            jobLog.WriteEntry(this, "Video Codec : " + _videoCodec, Log.LogEntryType.Debug);
            if (String.IsNullOrWhiteSpace(_videoCodec))
                _error = true;

            _audioCodec = VideoParams.AudioFormat(SourceVideo);
            jobLog.WriteEntry(this, "Audio Codec : " + _audioCodec, Log.LogEntryType.Debug);
            if (String.IsNullOrWhiteSpace(_audioCodec))
                _error = true;

            _fps = VideoParams.FPS(SourceVideo);
            jobLog.WriteEntry(this, "Video FPS : " + _fps.ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
            if (_fps <= 0)
                _error = true;

            _width = VideoParams.VideoWidth(SourceVideo);
            jobLog.WriteEntry(this, "Video Width : " + _width.ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
            if (_width <= 0)
                _error = true;

            _height = VideoParams.VideoHeight(SourceVideo);
            jobLog.WriteEntry(this, "Video Height : " + _height.ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
            if (_height <= 0)
                _error = true;

            _duration = VideoParams.VideoDuration(SourceVideo);
            jobLog.WriteEntry(this, "Video Duration : " + _duration.ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
            if (_duration <= 0)
                _error = true;

            _audioDelay = VideoParams.AudioDelay(SourceVideo);
            jobLog.WriteEntry(this, "Audio Delay : " + _audioDelay.ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);

            _scanType = VideoParams.VideoScanType(SourceVideo);
            jobLog.WriteEntry(this, "Video Scan Type : " + _scanType.ToString(), Log.LogEntryType.Debug);

            if (_scanType == ScanType.Unknown && _detectInterlacing) // If we couldn't find it lets try ffmpeg - avoid unnecessary cycles if not required
            {
                jobLog.WriteEntry(this, "Scan type unknown, trying with FFMPEGMediaInfo", Log.LogEntryType.Debug);

                _ffmpegStreamInfo = new FFmpegMediaInfo(SourceVideo, _jobStatus, _jobLog, 0, 0, _ignoreSuspend); // Run interlace detection with defaults
                if (_ffmpegStreamInfo.Success && !_ffmpegStreamInfo.ParseError)
                {
                    // Now calcuate whether it's Interlaced or Progressive based on the Multi Frame Interlaced Detection Results
                    long totalInterlaced = _ffmpegStreamInfo.MFInterlaceDetectionResults.BFF + _ffmpegStreamInfo.MFInterlaceDetectionResults.TFF;
                    long totalProgressive = _ffmpegStreamInfo.MFInterlaceDetectionResults.Progressive;
                    long totalUndetermined = _ffmpegStreamInfo.MFInterlaceDetectionResults.Undetermined; // TODO: What to do with this?

                    if (totalInterlaced == 0 && totalProgressive == 0) // Boundary conditions
                        _scanType = ScanType.Unknown;
                    else if (totalInterlaced == 0) // Avoid divide by zero exception
                        _scanType = ScanType.Progressive;
                    else
                    {
                        double PtoIRatio = totalProgressive / totalInterlaced; // See below comment

                        // Refer to this, how to tell if the video is interlaced or telecine
                        // http://forum.videohelp.com/threads/295007-Interlaced-or-telecined-how-to-tell?p=1797771&viewfull=1#post1797771
                        // It is a statistical ratio, telecine has approx split of 3 progressive and 2 interlaced (i.e. ratio of about 1.5 progressive to interlaced)
                        // TODO: We need to revisit the logic below for telecine, interlaced or progressive detection (check idet filter for updates ffmpeg ticket #3073)
                        if ((totalProgressive == 0) && (totalProgressive == 0)) // Unknown - could not find
                            _scanType = ScanType.Unknown;
                        else if ((PtoIRatio > TELECINE_LOW_P_TO_I_RATIO) && (PtoIRatio < TELECINE_HIGH_P_TO_I_RATIO)) // Let us keep a band to measure telecine ratio, see comment above
                            _scanType = ScanType.Telecine;
                        else if (PtoIRatio <= TELECINE_LOW_P_TO_I_RATIO) // We play safe, more interlaced than progressive
                            _scanType = ScanType.Interlaced;
                        else if (PtoIRatio >= TELECINE_HIGH_P_TO_I_RATIO) // Progressive has the clear lead
                            _scanType = ScanType.Progressive;
                        else
                            _scanType = ScanType.Unknown; // No idea where we are
                    }

                    jobLog.WriteEntry(this, "FFMPEG Video Scan Type : " + _scanType.ToString(), Log.LogEntryType.Debug);
                }
                else
                    jobLog.WriteEntry(this, "Error reading scan type from FFMPEGMediaInfo", Log.LogEntryType.Warning);
            }

            // We don't get AudioChannel information here as it interfers with FFMPEG
            /*mi.Option("Inform", "Audio; %Channels%");
            int.TryParse(mi.Inform(), out _audioChannels);
            jobLog.WriteEntry(this, "Audio Channels : " + _audioChannels.ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);*/

            // Supplement with extracting Video and Audio information (sometimes MediaInfo fails) using FFMPEG and selected the Audio Language specified
            _jobLog.WriteEntry(this, "Supplementing Media information using FFMPEG", Log.LogEntryType.Information);
            _ffmpegStreamInfo = new FFmpegMediaInfo(SourceVideo, _jobStatus, _jobLog, _ignoreSuspend); // this may be called from the UI request
            if (_ffmpegStreamInfo.Success && !_ffmpegStreamInfo.ParseError)
            {
                // Store the video information (there's only 1 video per file)
                _width = _ffmpegStreamInfo.MediaInfo.VideoInfo.Width;
                _height = _ffmpegStreamInfo.MediaInfo.VideoInfo.Height;
                if ((_fps <= 0) || ((_fps > _ffmpegStreamInfo.MediaInfo.VideoInfo.FPS) && (_ffmpegStreamInfo.MediaInfo.VideoInfo.FPS > 0))) // Check _fps, sometimes MediaInfo get it below 0 or too high (most times it's reliable)
                    _fps = _ffmpegStreamInfo.MediaInfo.VideoInfo.FPS;
                else
                    _ffmpegStreamInfo.MediaInfo.VideoInfo.FPS = _fps; // Store the value from MediaInfo, more reliable
                _duration = _ffmpegStreamInfo.MediaInfo.VideoInfo.Duration;
                _videoCodec = _ffmpegStreamInfo.MediaInfo.VideoInfo.VideoCodec;
                _videoStream = _ffmpegStreamInfo.MediaInfo.VideoInfo.Stream;
                _videoPID = _ffmpegStreamInfo.MediaInfo.VideoInfo.PID; // video PID
                
                // Default Check if all audio streams have same codec, if so populate the field for later use during reading profiles
                for (int i = 0; i < _ffmpegStreamInfo.AudioTracks; i++)
                {
                    if (i == 0)
                        _audioCodec = _ffmpegStreamInfo.MediaInfo.AudioInfo[i].AudioCodec; // baseline the codec name
                    else if (_audioCodec != _ffmpegStreamInfo.MediaInfo.AudioInfo[i].AudioCodec)
                    {
                        _audioCodec = ""; // All codecs are not the same, reset it and let the encoder figure it out
                        break; // we're done here
                    }
                }

                // Default check if all audio streams have same channels, if so populate the field for later use during reading profiles
                for (int i = 0; i < _ffmpegStreamInfo.AudioTracks; i++)
                {
                    if (i == 0)
                        _audioChannels = _ffmpegStreamInfo.MediaInfo.AudioInfo[i].Channels; // baseline the channels
                    else if (_audioChannels != _ffmpegStreamInfo.MediaInfo.AudioInfo[i].Channels)
                    {
                        _audioChannels = 0; // All channels are not the same, reset it and let the encoder figure it out
                        break; // we're done here
                    }
                }

                // Audio parameters - find the best Audio channel for the selected language or best audio track if there are imparired tracks otherwise by default the encoder will select the best audio channel (encoders do not do a good job of ignoring imparired tracks)
                bool selectedTrack = false;
                if ((!String.IsNullOrEmpty(_requestedAudioLanguage) || (_ffmpegStreamInfo.ImpariedAudioTrackCount > 0)) && (_ffmpegStreamInfo.AudioTracks > 1)) // More than 1 audio track to choose from and either we have a language match request or a presence of an imparied channel (likely no audio)
                {
                    for (int i = 0; i < _ffmpegStreamInfo.AudioTracks; i++)
                    {
                        bool processTrack = false; // By default we don't need to process

                        // Language selection check, if the user has picked a specific language code, look for it
                        // If we find a match, we look the one with the highest number of channels in it
                        if (!String.IsNullOrEmpty(_requestedAudioLanguage))
                        {
                            if ((_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Language.ToLower() == _requestedAudioLanguage) && (_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Channels > 0))
                            {
                                if (selectedTrack)
                                {
                                    if (!( // take into account impaired tracks (since impaired tracks typically have no audio)
                                        ((_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Channels > _audioChannels) && !_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Impaired) || // PREFERENCE to non-imparied Audio tracks with the most channels
                                        ((_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Channels > _audioChannels) && _selectedAudioImpaired) || // PREFERENCE to Audio tracks with most channels if currently selected track is impaired
                                        (!_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Impaired && _selectedAudioImpaired) // PREFER non impaired audio over currently selected impaired
                                        ))
                                        continue; // we have found a lang match, now we are looking for more channels only now
                                }
                             
                                processTrack = true; // All conditions met, we need to process this track
                            }
                        }
                        else if (_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Channels > 0)// we have a imparied audio track, select the non impaired track with the highest number of tracks or bitrate or frequency
                        {
                            if (selectedTrack)
                            {
                                if (!( // take into account impaired tracks (since impaired tracks typically have no audio)
                                    ((_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Channels > _audioChannels) && !_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Impaired) || // PREFERENCE to non-imparied Audio tracks with the most channels
                                    ((_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Channels > _audioChannels) && _selectedAudioImpaired) || // PREFERENCE to Audio tracks with most channels if currently selected track is impaired
                                    (!_ffmpegStreamInfo.MediaInfo.AudioInfo[i].Impaired && _selectedAudioImpaired) // PREFER non impaired audio over currently selected impaired
                                    ))
                                    continue; // we have found a lang match, now we are looking for more channels only now
                            }

                            processTrack = true; // All conditions met, we need to process this track
                        }

                        if (processTrack) // We need to process this track
                        {
                            _audioChannels = _ffmpegStreamInfo.MediaInfo.AudioInfo[i].Channels;
                            _audioStream = _ffmpegStreamInfo.MediaInfo.AudioInfo[i].Stream; // store the stream number for the selected audio channel
                            _audioCodec = _ffmpegStreamInfo.MediaInfo.AudioInfo[i].AudioCodec;
                            _audioPID = _ffmpegStreamInfo.MediaInfo.AudioInfo[i].PID; // Audio PID
                            _audioTrack = i; // Store the audio track number we selected
                            _audioLanguage = _ffmpegStreamInfo.MediaInfo.AudioInfo[i].Language.ToLower(); // this is what we selected
                            _selectedAudioImpaired = _ffmpegStreamInfo.MediaInfo.AudioInfo[i].Impaired; // Is this an imparied audio track?
                            selectedTrack = true; // We found a suitable track

                            if (!String.IsNullOrEmpty(_requestedAudioLanguage))
                                _jobLog.WriteEntry(this, "Found Audio Language match for language" + " " + _requestedAudioLanguage.ToUpper() + ", " + "Audio Stream" + " " + _audioStream.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Audio Track") + " " + _audioTrack.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Channels") + " " + _audioChannels.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Codec") + " " + _audioCodec + " Impaired " + _selectedAudioImpaired.ToString(), Log.LogEntryType.Debug);
                            else
                                _jobLog.WriteEntry(this, "Compensating for audio impaired tracks, selected track with language" + " " + _requestedAudioLanguage.ToUpper() + ", " + "Audio Stream" + " " + _audioStream.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Audio Track") + " " + _audioTrack.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Channels") + " " + _audioChannels.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Codec") + " " + _audioCodec + " Impaired " + _selectedAudioImpaired.ToString(), Log.LogEntryType.Debug);
                        }
                    }

                    if (!selectedTrack)
                        _jobLog.WriteEntry(this, ("Could not find a match for selected Audio Language Code") + " " + _requestedAudioLanguage + ", letting encoder choose best audio language", Log.LogEntryType.Warning);
                    else
                        _jobLog.WriteEntry(this, ("Selected Audio Stream") + " " + _audioStream.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Audio Track") + " " + _audioTrack.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Channels") + " " + _audioChannels.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Codec") + " " + _audioCodec + ", Impaired " + _selectedAudioImpaired.ToString(), Log.LogEntryType.Debug);
                }
                else if (_ffmpegStreamInfo.AudioTracks == 1) // We have just one audio track, then populate the information otherwise the encoding operations will have a hard time determining audio information
                {
                    if (_ffmpegStreamInfo.MediaInfo.AudioInfo[0].Channels > 0)
                    {
                        _audioChannels = _ffmpegStreamInfo.MediaInfo.AudioInfo[0].Channels;
                        _audioStream = _ffmpegStreamInfo.MediaInfo.AudioInfo[0].Stream; // store the stream number for the selected audio channel
                        _audioCodec = _ffmpegStreamInfo.MediaInfo.AudioInfo[0].AudioCodec;
                        _audioPID = _ffmpegStreamInfo.MediaInfo.AudioInfo[0].PID; // Audio PID
                        _audioTrack = 0; // Store the audio track number we selected
                        _audioLanguage = _ffmpegStreamInfo.MediaInfo.AudioInfo[0].Language.ToLower(); // this is what we selected
                        _selectedAudioImpaired = _ffmpegStreamInfo.MediaInfo.AudioInfo[0].Impaired; // Is this an imparied audio track?

                        _jobLog.WriteEntry(this, "Only one audio track present, " + ("Audio Stream") + " " + _audioStream.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Audio Track") + " " + _audioTrack.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Channels") + " " + _audioChannels.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Codec") + " " + _audioCodec + " Impaired " + _selectedAudioImpaired.ToString(), Log.LogEntryType.Debug);
                    }
                }
                else
                {
                    _jobLog.WriteEntry(this, ("Audio Stream") + " " + _audioStream.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Audio Track") + " " + _audioTrack.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Channels") + " " + _audioChannels.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + ("Codec") + " " + _audioCodec + ", Impaired " + _selectedAudioImpaired.ToString(), Log.LogEntryType.Debug);
                    _jobLog.WriteEntry(this, "No audio language selected, letting encoder choose best audio language", Log.LogEntryType.Warning);
                }

                _error = false; // all good now
            }
            else
                _error = true;
            
            if (_error)
            {
                _jobLog.WriteEntry(this, ("Unable to read media information using FFMPEG or MediaInfo"), Log.LogEntryType.Error);
                return;
            }

            // Get the video properties for the original video
            _jobLog.WriteEntry(this, "Reading Original File Media information", Log.LogEntryType.Information);
            _originalFileFFmpegStreamInfo = new FFmpegMediaInfo(_originalFileName, _jobStatus, _jobLog, _ignoreSuspend);
            if (!_originalFileFFmpegStreamInfo.Success || _originalFileFFmpegStreamInfo.ParseError)
                _jobLog.WriteEntry(this, ("Unable to read media information using FFMPEG"), Log.LogEntryType.Warning);

            if (_skipCropDetect)
                _jobLog.WriteEntry(this, "Skipping crop information", Log.LogEntryType.Information);
            else
                UpdateCropInfo(jobLog);
        }
Beispiel #41
0
 private static void WriteToLog(string scanNumber, ScanType scanType, string direction, string activity)
 {
     Database.Command(
            "INSERT INTO learnerActivity(learnerNumber,dateTime,activity,division,username, details, type, session) VALUES ('" +
            scanNumber + "','" + DateTime.Now.ToString("yyyyMMddHHmmss") + "','" + activity + "','" +
            GlobalProperties.loggedOnUserDivisionAbrev + "','" + GlobalProperties.loggedOnUser + "','" + direction + "','" + GetScanTypeString(scanType) + "','" +
            clsFunctions.GetCurrentSession() + "')");
 }
Beispiel #42
0
        private string GetScanTaskParamString(ScanType type, Event scanEvent)
        {
            string resultCollection = type.ToString();
            if (type == ScanType.Official)
            {
                resultCollection = MatchScanner.OfficialResultsCollectionId;
            }
            else if (type == ScanType.Manual)
            {
                // Manual uses a random result collection.
                resultCollection = Guid.NewGuid().ToString("N");
            }

            string gameIdString = scanEvent.Game.GameId.ToString();

            DateTime? startTime;
            if (type == ScanType.TestPass 
                || type == ScanType.Manual)
            {
                startTime = Time.UtcNow;
            }
            else
            {
                startTime = null;
            }

            TimeSpan refreshTime = scanEvent.Game.MatchHistoryRefreshTime;

            return String.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8}", 
                scanEvent.Id, 
                resultCollection, 
                scanEvent.LiveStart.ToFileTimeUtc().ToString(),
                scanEvent.EventEnd.ToFileTimeUtc().ToString(), 
                gameIdString, 
                type.ToString(), 
                startTime.HasValue ? startTime.Value.ToFileTimeUtc().ToString() : "null",
                refreshTime.Ticks.ToString(),
                scanEvent.Game.NumMatchesPerQuery);
        }
        protected override void StartScan()
        {
            base.StartScan();

            if (ConnectionManagerMode == Mode.Scan)
            {
                UpdateAvailablePorts();
                _scanType = ScanType.None;
            }
        }
Beispiel #44
0
 private static string GetScanTypeString(ScanType scanType)
 {
     string type = "";
     switch (scanType)
     {
         case ScanType.Attendance:
             type = "Attendance";
             break;
         case ScanType.Exam:
             type = "Exam";
             break;
         case ScanType.Meeting:
             type = "Meeting";
             break;
         case ScanType.Workshop:
             type = "Workshop";
             break;
     }
     return type;
 }
Beispiel #45
0
 /// <summary>
 ///     Perform a TCP port scan on the specified ports with service detection and OS detection.
 /// </summary>
 /// <param name="scanType">The type of scan to perform</param>
 /// <param name="ports">A string detailing which ports to scan (e.g., "10-20,33")</param>
 /// <returns>A ScanResult object detailing the results of the port scan</returns>
 public ScanResult PortScan(ScanType scanType, string ports)
 {
     NmapContext ctx = _portScanCommon(scanType, ports);
     return new ScanResult(ctx.Run());
 }
Beispiel #46
0
 public void ScanRequest(
     ScanType scanType,
     UInt32 scanChannels,
     byte scanDuration,
     byte channelPage,
     SecurityOptions securityOptions,
     ScanChannelConfirmHandler handler)
 {
     TaskScanRequest task = new TaskScanRequest(
         scanType,
         scanChannels,
         scanDuration,
         channelPage,
         securityOptions,
         handler);
     if (!_taskQueue.Add(task) && handler != null)
     {
         handler.Invoke(this, MacEnum.Congested, scanType, channelPage, scanChannels, null, null);
     }
 }
Beispiel #47
0
        /// <summary>
        ///     Build an nmap context with the specified options
        /// </summary>
        /// <param name="scanType">The desired type of scan to perform</param>
        /// <param name="ports">The ports to scan (null of empty for default ports)</param>
        /// <returns>An nmap context for performing the desired scan</returns>
        private NmapContext _portScanCommon(ScanType scanType, string ports)
        {
            NmapContext ctx = GetContext();

            // We always try to detect the OS and the service versions
            ctx.Options.AddAll(new[]
                {
                    NmapFlag.ServiceVersion,
                    NmapFlag.OsDetection
                });

            // Add the appropriate flag if we're not performing a default scan
            if (scanType != ScanType.Default)
            {
                ctx.Options.Add(_scanTypeToNmapFlag[scanType]);
            }

            // Unless we specify UDP only, then perform a UDP scan in the same run
            if (scanType != ScanType.Default && scanType != ScanType.Udp)
            {
                ctx.Options.Add(NmapFlag.UdpScan);
            }

            // If we have a port specification, then use it
            if (ports != null && !string.IsNullOrEmpty(ports))
            {
                ctx.Options.Add(NmapFlag.PortSpecification, ports);
            }

            return ctx;
        }
Beispiel #48
0
 private int GetScanTaskPriority(ScanType type)
 {
     if (type == ScanType.Official)
     {
         return int.MaxValue;
     }
     else if (type == ScanType.TestPass)
     {
         return 10;
     }
     else if (type == ScanType.Manual)
     {
         return 9;
     }
     else
     {
         throw new ArgumentException();
     }
 }
        // Perform scan to find connected systems
        protected override void DoWorkScan()
        {
            // First try if currentConnection is open or can be opened
            var activeConnection = false;

            switch (_scanType)
            {
                case ScanType.None:
                    try
                    {
                        activeConnection = TryConnection() == DeviceStatus.Available;
                    }
                    catch
                    {
                        // Do nothing
                    }
                    _scanType = ScanType.Quick;
                    break;
                case ScanType.Quick:
                    try
                    {
                        activeConnection = QuickScan();
                    }
                    catch
                    {
                        // Do nothing
                    }
                    _scanType = ScanType.Thorough;
                    break;
                case ScanType.Thorough:
                    try
                    {
                        activeConnection = ThoroughScan();
                    }
                    catch
                    {
                        // Do nothing
                    }
                    _scanType = ScanType.Quick;
                    break;
            }

            // Trigger event when a connection was made
            if (activeConnection)
            {
                ConnectionFoundEvent();
            }
        }
Beispiel #50
0
 private string GetScanTaskId(ScanType type, Event scanEvent)
 {
     return string.Format("{0}{1}", type.ToString(), scanEvent.Id);
 }
        /// <summary>
        /// Performs scan
        /// </summary>
        private void Run()
        {
            if (!scanRunning)
            {
                this.RunButtonText = "Stop";
                this.OrgItems.Clear();
            }
            else
            {
                CancelScan();
                return;
            }

            scanRunning = true;

            // Clear results
            this.Progress = 0;
            this.ProgressMessage = "Scan Started";

            SetupColumns();

            // Build scan parameters
            object list;
            switch (this.RunType)
            {
                case ScanType.Directory:
                    // Get folders from combo box
                    List<OrgFolder> scanDirs;
                    if (this.SelectedRunSelection == OrgFolder.AllFolders)
                        scanDirs = Settings.ScanDirectories.ToList();
                    else
                    {
                        scanDirs = new List<OrgFolder>() { (OrgFolder)this.SelectedRunSelection };
                    }
                    list = scanDirs;
                    break;

                case ScanType.TvRename:
                case ScanType.TvMissing:
                    List<Content> shows;
                    if (this.SelectedRunSelection == TvShow.AllShows)
                        shows = Organization.Shows.GetScannableContent(true, this.RunType);
                    else
                    {
                        shows = new List<Content>();
                        shows.Add((TvShow)this.SelectedRunSelection);
                    }
                    list = shows;
                    break;
                case ScanType.TvFolder:
                    List<ContentRootFolder> tvFolders;
                    if (this.SelectedRunSelection == ContentRootFolder.AllTvFolders)
                        tvFolders = Settings.TvFolders.ToList();
                    else
                        tvFolders = new List<ContentRootFolder>() { (ContentRootFolder)this.SelectedRunSelection };
                    list = tvFolders;
                    break;
                case ScanType.MovieFolder:
                    List<ContentRootFolder> movieFolders;
                    if (this.SelectedRunSelection == ContentRootFolder.AllMoviesFolders)
                        movieFolders = Settings.MovieFolders.ToList();
                    else
                        movieFolders = new List<ContentRootFolder>() { (ContentRootFolder)this.SelectedRunSelection };
                    list = movieFolders;
                    break;
                default:
                    throw new Exception("Unknown scan type");
            }

            // Start worker if not busy, otherwise cancel current scan and set rescan required flag
            if (!scanWorker.IsBusy)
            {
                currentScan = this.RunType;
                scanWorker.RunWorkerAsync(new object[] { currentScan, list, this.Fast, this.ReuseResults });
                lastRunScan = currentScan;
            }
            else
            {
                rescanRequired = true;
                CancelScan();
            }
        }
Beispiel #52
0
        private void ScanInLearner(string scanNumber, ScanType scanType, bool accessGranted)
        {
            if (LearnerExistsQuery.Run(scanNumber,GlobalProperties.loggedOnUserDivison))
            {
                var details = Database.Row("learner_details",
                                           "LearnerNumber = '" + scanNumber + "' AND division = '" +
                                           GlobalProperties.loggedOnUserDivison + "'");

                WriteToLog(scanNumber, scanType, "In", (accessGranted ? "Access Granted" : "Access Denied - " + _accessDeniedReason));

                Database.Command("INSERT INTO scannedLearners VALUES ('" + scanNumber + "','" + GlobalProperties.loggedOnUserDivison + "','" + clsFunctions.GetCurrentSession() + "','" + DateTime.Now.ToString("yyyyMMddhhmmss") +
                    "','" + Convert.ToString(details["name"]) + " " + Convert.ToString(details["Surname"]) + "','" + scanType + "','" +
                 Database.Retrieve("learnerActivity","DATE(`dateTime`) = " +
                    DateTime.Today.ToString("yyyyMMdd") + " AND learnerNumber = '" + scanNumber + "' AND division = '" + GlobalProperties.loggedOnUserDivisionAbrev +
                    "' AND details = 'In'","MAX(idLearnerActivity)") + "')");
            }
            else
            {
                MessageBox.Show(@"Student doesn't exist");
            }
        }
	// Scan a directory to collect up all entries that match
	// the specified search criteria, returning FileSystemInfo's.
	internal static Object ScanDirectoryForInfos
				(String path, String searchPattern,
				 ScanType scanType, Type arrayType)
			{
				Regex regex;
				ArrayList list;
				InternalFileInfo[] entries;
				Errno error;
				int posn;
				String filename;
				FileType type;

				// Get all files in the directory.
				error = DirMethods.GetFilesInDirectory(path, out entries);
				if(error != Errno.Success)
				{
					HandleErrorsDir(error);
				}
				if(entries == null)
				{
					return new String [0];
				}

				// Convert the search pattern into a regular expression.
				if(searchPattern == null)
				{
					regex = null;
				}
				else
				{
					regex = new Regex(searchPattern, RegexSyntax.Wildcard);
				}

				// Scan the file list and collect up matching entries.
				list = new ArrayList (entries.Length);
				for(posn = 0; posn < entries.Length; ++posn)
				{
					filename = entries[posn].fileName;
					if(filename == "." || filename == "..")
					{
						continue;
					}
					type = entries[posn].fileType;
					switch(scanType)
					{
						case ScanType.Directories:
						{
							if(type != FileType.directory)
							{
								continue;
							}
						}
						break;

						case ScanType.Files:
						{
							if(type == FileType.directory)
							{
								continue;
							}
						}
						break;

						default: break;
					}
					if(regex != null && !regex.Match(filename))
					{
						continue;
					}
					if(type == FileType.directory)
					{
						list.Add(new DirectoryInfo
									(Path.Combine(path, filename)));
					}
					else
					{
						list.Add(new FileInfo(Path.Combine(path, filename)));
					}
				}

				// Dispose of the regular expression.
				if(regex != null)
				{
					regex.Dispose();
				}

				// Return the list of strings to the caller.
				return list.ToArray(arrayType);
			}
        protected override void StartScan()
        {
            base.StartScan();

            if (ConnectionManagerMode == Mode.Scan)
            {
                _scanType = ScanType.None;
            }
        }
Beispiel #55
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public CommandStatus Scan(ScanDirection dir, uint lba, ScanType type)
        {
            if (m_logger != null)
            {
                string args = dir.ToString() + ", " + lba.ToString() + ", " + type.ToString();
                m_logger.LogMessage(new UserMessage(UserMessage.Category.Debug, 8, "Bwg.Scsi.Device.Scan(" + args + ")"));
            }

            if (type == ScanType.Reserved)
                throw new Exception("type parameter is of type Reserved");

            using (Command cmd = new Command(ScsiCommandCode.Scan, 12, 0, Command.CmdDirection.None, 10))
            {
                if (dir == ScanDirection.Reverse)
                    cmd.SetCDB8(1, 0x10);
                cmd.SetCDB32(2, lba);
                cmd.SetCDB8(9, (byte)((byte)type << 6));

                CommandStatus st = SendCommand(cmd);
                if (st != CommandStatus.Success)
                    return st;
            }

            return CommandStatus.Success;
        }
Beispiel #56
0
 public TaskScanRequest(
     ScanType scanType,
     UInt32 scanChannels,
     byte scanDuration,
     byte channelPage,
     SecurityOptions securityOptions,
     ScanChannelConfirmHandler handler)
     : base(TaskType.ScanRequest)
 {
     this.scanType = scanType;
     this.scanChannels = scanChannels;
     this.scanDuration = scanDuration;
     this.channelPage = channelPage;
     this.securityOptions = securityOptions;
     this.handler = handler;
 }
        // Perform scan to find connected systems
        protected override void DoWorkScan()
        {
            if (Thread.CurrentThread.Name == null) Thread.CurrentThread.Name = "BluetoothConnectionManager";
            var activeConnection = false;

            // Starting scan
            if (_scanType == ScanType.None) 
            {
                _scanType = ScanType.Quick;
            }

            switch (_scanType)
            {
                case ScanType.Quick:
                    try { activeConnection = QuickScan(); } catch {
                        //Do nothing 
                    }
                    _scanType = ScanType.Thorough;
                    break;
                case ScanType.Thorough:
                    try { activeConnection = ThoroughScan(); } catch {
                        //Do nothing 
                    }
                    _scanType = ScanType.Quick;
                    break;
            }

            // Trigger event when a connection was made
            if (activeConnection)
            {
                ConnectionFoundEvent();
            } 
        }