Beispiel #1
0
        public void Delete(string username, string refreshToken)
        {
            var tokenToDelete = _userRefreshTokens.FirstOrDefault(x => x.UserName == username);

            if (tokenToDelete != null && tokenToDelete.RefreshToken == refreshToken)
            {
                _userRefreshTokens.TryTake(out tokenToDelete);
            }
        }
Beispiel #2
0
 public WorkflowDefinition GetDefinition(string workflowId, int?version = null)
 {
     if (version.HasValue)
     {
         var entry = _registry.FirstOrDefault(x => x.Item1 == workflowId && x.Item2 == version.Value);
         // TODO: What in the heck does Item3 mean?
         return(entry?.Item3);
     }
     else
     {
         var entry = _registry.Where(x => x.Item1 == workflowId).OrderByDescending(x => x.Item2)
                     .FirstOrDefault();
         return(entry?.Item3);
     }
 }
Beispiel #3
0
        private void PopulateGridWithCells()
        {
            cells = new BlockingCollection <Cell>();

            for (int i = 0; i < myGrid.ColumnDefinitions.Count; i++)
            {
                for (int j = 0; j < myGrid.RowDefinitions.Count; j++)
                {
                    var cell = new Cell(i, j);
                    Grid.SetColumn(cell, i);
                    Grid.SetRow(cell, j);
                    cells.Add(cell);
                    myGrid.Children.Add(cell);
                }
            }

            foreach (var cell in cells)
            {
                foreach (var index in KeyValuePairs)
                {
                    int a = cell.X + index.Key, b = cell.Y + index.Value;
                    if (a < 0 || b < 0 || a > myGrid.RowDefinitions.Count - 1 || b > myGrid.ColumnDefinitions.Count - 1)
                    {
                        continue;
                    }
                    cell.AddChild(cells.FirstOrDefault(x => x.X == a && x.Y == b));
                }
            }
        }
Beispiel #4
0
        public AudioFrame Poll(BlockingCollection <AudioFrame> audioFrame)
        {
            AudioFrame returnVal = audioFrame.FirstOrDefault <AudioFrame>();

            audioFrame.TryTake(out returnVal);
            return(returnVal);
        }
Beispiel #5
0
        private void MyGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var    point = Mouse.GetPosition(myGrid);
            int    row = 0, col = 0;
            double accumulatedHeight = 0.0, accumulatedWidth = 0.0;

            foreach (var rowDefinition in myGrid.RowDefinitions)
            {
                accumulatedHeight += rowDefinition.ActualHeight;
                if (accumulatedHeight >= point.Y)
                {
                    break;
                }
                row++;
            }

            foreach (var columnDefinition in myGrid.ColumnDefinitions)
            {
                accumulatedWidth += columnDefinition.ActualWidth;
                if (accumulatedWidth >= point.X)
                {
                    break;
                }
                col++;
            }

            var cell = cells.FirstOrDefault(x => x.X == col && x.Y == row);

            cell.Infect();
        }
Beispiel #6
0
        /// <summary>
        /// Сохраняет в БД результаты парсинга
        /// </summary>
        /// <param name="resourceItemsBc">resourceItemsBc</param>
        /// <param name="releasesBc">releasesBc</param>
        private void SaveResults(BlockingCollection <ResourceItemEntity> resourceItemsBc,
                                 BlockingCollection <AlbumInfoRelease> releasesBc)
        {
            if (!resourceItemsBc.Any() && !releasesBc.Any())
            {
                throw new AlbumInfoReleaseException(Helper.EmptyReleaseException);
            }

            var resourceItems = resourceItemsBc.ToList();

            foreach (var resourceItem in resourceItems)
            {
                //находим соответствующий релиз
                var release = releasesBc.FirstOrDefault(r => r.ResourceInternalId == resourceItem.ResourceInternalId);

                if (release != null)
                {
                    var music   = MapAlbumInfoReleaseToMusic(release);
                    var musicId = SaveRelease(music);
                    resourceItem.MusicId = musicId;

                    SaveMusicTrack(release.TrackList, musicId);

                    SaveResourceItem(resourceItem);
                }
                else
                {
                    throw new AlbumInfoReleaseException(
                              string.Format(Helper.ParsReleaseException, resourceItem.ResourceInternalId));
                }
            }
        }
        public override void RemoveClient(NetworkClient Client)
        {
            CityInfo Info = CityServers.FirstOrDefault(x => x.Client == Client);

            if (CityServers.TryTake(out Info))
            {
                lock (NetworkFacade.ClientListener.Clients)
                {
                    PacketStream ClientPacket = new PacketStream((byte)PacketType.CITY_SERVER_OFFLINE, 0);
                    ClientPacket.WriteString(Info.Name);
                    ClientPacket.WriteString(Info.Description);
                    ClientPacket.WriteString(Info.IP);
                    ClientPacket.WriteInt32(Info.Port);
                    ClientPacket.WriteByte((byte)Info.Status);
                    ClientPacket.WriteUInt64(Info.Thumbnail);
                    ClientPacket.WriteString(Info.UUID);
                    ClientPacket.WriteUInt64(Info.Map);

                    foreach (NetworkClient Receiver in NetworkFacade.ClientListener.Clients)
                    {
                        Receiver.SendEncrypted((byte)PacketType.CITY_SERVER_OFFLINE, ClientPacket.ToArray());
                    }
                }

                Debug.WriteLine("Removed CityServer!");
            }
        }
Beispiel #8
0
 protected override string PeekJson(out long length)
 {
     length = _Queue.Count;
     if (length < 1)
     {
         return(null);
     }
     return(_Queue.FirstOrDefault());
 }
Beispiel #9
0
        public AudioFrame Poll(BlockingCollection <AudioFrame> audioFrame, long timeout, TimeUnit unit)
        {
            AudioFrame returnVal = audioFrame.FirstOrDefault <AudioFrame>();

            audioFrame.TryTake(out returnVal);
            return(returnVal);

            unit.wait(timeout);
            return(null);
        }
Beispiel #10
0
        void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ItemLog resultItemLog = e.Result as ItemLog;

            ItemWorker itemWorker = itemWorkers.FirstOrDefault(t => t.BackgroundWorker == (BackgroundWorker)sender);

            itemWorker.DesignerItem.State = resultItemLog.ExecutionSuccessful ? ItemState.Stopped : ItemState.Error;

            ProgressReport progressReport = new SDK.ProgressReport()
            {
                State = resultItemLog.ExecutionSuccessful ?
                        ItemEvent.StoppedSuccessful :
                        ItemEvent.StoppedWithError,
                DesignerItem = itemWorker.DesignerItem,
                Message      = resultItemLog.ExecutionSuccessful ? "Successful" : "Error"
            };

            progress.Report(progressReport);
        }
Beispiel #11
0
        public static void Modify(CorporateEntity entity)
        {
            var item = DataStore.FirstOrDefault(e => e.Id == entity.Id);

            if (item != null)
            {
                if (!entity.InternalReference.Equals(Guid.Empty))
                {
                    item.InternalReference = entity.InternalReference;
                }
                item.Name = entity.Name;
            }
        }
Beispiel #12
0
        void IbetEnScoreEventChanged(MatchBrokerDTO sender, EventArgs e)
        {
            try
            {
                bool isValidLang = false;

                if (HasCheckAllLeagues)
                {
                    isValidLang = true;
                }
                else
                {
                    isValidLang = FilterLeagues.Any(sender.LeagueName.ToUpper().Contains);
                }

                if (isValidLang && !DataContainer.LeaguesDenyKeywords.Any(sender.LeagueName.ToUpper().Contains) &&
                    (!DataContainer.MatchsDenyKeywords.Any(sender.HomeTeamName.ToUpper().Contains) ||
                     !DataContainer.MatchsDenyKeywords.Any(sender.AwayTeamName.ToUpper().Contains)))
                {
                    UpdateWriteTextLog(string.Format("GOAL!!!! {0} vs {1} score {2}-{3} ", sender.HomeTeamName,
                                                     sender.AwayTeamName, sender.HomeScore, sender.AwayScore), eLogTextType.Highlight);

                    var checkMatchScored = ScoredMatchs.FirstOrDefault(m => String.Equals(m.HomeTeamName, sender.HomeTeamName, StringComparison.CurrentCultureIgnoreCase) ||
                                                                       String.Equals(m.AwayTeamName, sender.AwayTeamName, StringComparison.CurrentCultureIgnoreCase));
                    if (checkMatchScored == null)
                    {
                        ScoredMatchs.Add(sender);
                    }
                    else
                    {
                        checkMatchScored.HomeScore = sender.HomeScore;
                        checkMatchScored.AwayScore = sender.AwayScore;
                        if ((SumScoreMaxBuy != 0 && (sender.HomeScore + sender.AwayScore) <= SumScoreMaxBuy) || SumScoreMaxBuy == 0)
                        {
                            checkMatchScored.CountTimeCheck = 0;
                            checkMatchScored.FinishCheck    = false;
                        }
                        else
                        {
                            checkMatchScored.FinishCheck = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Parses captured data into the packet
        /// </summary>
        /// <param name="rawCapture">Captured data</param>
        protected void ParsePacket(RawCapture rawCapture)
        {
            try
            {
                var packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);

                var tcpPacket = packet.Extract <TcpPacket>();
                var ipPacket  = packet.Extract <IPPacket>();

                if (tcpPacket == null || ipPacket == null)
                {
                    return;
                }

                var matchedImporter = importers.FirstOrDefault(x => x.IsRunning && !x.IsDisabled() && x.Match(tcpPacket, ipPacket));

                if (matchedImporter == null)
                {
                    return;
                }

                var payloadData = tcpPacket.PayloadData;

                if (payloadData == null || payloadData.Length == 0)
                {
                    return;
                }

                var capturedPacket = new CapturedPacket
                {
                    Bytes            = tcpPacket.PayloadData,
                    Source           = new IPEndPoint(ipPacket.SourceAddress, tcpPacket.SourcePort),
                    Destination      = new IPEndPoint(ipPacket.DestinationAddress, tcpPacket.DestinationPort),
                    CreatedTimeStamp = rawCapture.Timeval.Date,
                    SequenceNumber   = tcpPacket.SequenceNumber
                };

                matchedImporter.AddPacket(capturedPacket);
            }
            catch (Exception e)
            {
                if (parsePacketLogErrorCounter < 5)
                {
                    LogProvider.Log.Error(this, "Failed to parse captured packet.", e);
                    parsePacketLogErrorCounter++;
                }
            }
        }
Beispiel #14
0
        public void NotifyPropertyChanged(ExcelNotityPropertyContext context)
        {
            if (isDisposed)
            {
                return;
            }

            if (contextItems.FirstOrDefault(i => i.ContextItem == context.ContextItem && !i.ChangeColor) != null)
            {
                return;
            }
            else
            {
                contextItems.Add(context);
            }
        }
Beispiel #15
0
        public static bool AllowExecution_OnPreviousErrorTest(ItemWorker itemWorker, BlockingCollection <ItemWorker> itemWorkers, BlockingCollection <ConnectionBase> connectionList)
        {
            IEnumerable <ConnectionBase> incomingConnections = GetIncomingConnections(itemWorker.DesignerItem.ID, connectionList);

            foreach (ConnectionBase connection in incomingConnections.Where(t => t.ConnectionType == ConnectorType.Default))
            {
                ItemWorker sourceItemWorker = itemWorkers.FirstOrDefault(t => t.DesignerItem.ID == connection.SourceID);

                bool allowExecution = AllowExecution_OnPreviousErrorTest_Recursive(sourceItemWorker, itemWorkers, connectionList);
                if (allowExecution == false)
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #16
0
        public async Task <List <PortScanResult> > PortScan(PortScanInput portScanInput, IPortClient portClient)
        {
            var result           = new BlockingCollection <PortScanResult>();
            var mergedInput      = MergePortScanInput(portScanInput);
            var addressPortPairs = mergedInput.ChunkInto(portScanInput.Workers);

            await AsyncHelper.ForEach(addressPortPairs, async (addressPortPair, token) =>
            {
                foreach (var pair in addressPortPair)
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }

                    var portResultEntry = await IsPortOpen(new PortInput
                    {
                        Address = pair.Address,
                        Retries = portScanInput.Retries,
                        Timeout = portScanInput.Timeout,
                        Port    = pair.Port
                    }, portClient);

                    var addressResult = result.FirstOrDefault(r => r.Address == pair.Address);
                    if (addressResult == null)
                    {
                        var portResult = new PortScanResult
                        {
                            Address = pair.Address,
                        };
                        portResult.Results.Add(portResultEntry);
                        result.Add(portResult);
                    }
                    else
                    {
                        addressResult.Results.Add(portResultEntry);
                    }
                    OnPortScanned(pair.Address, portResultEntry);
                }
            }, portScanInput.CancellationToken);

            var finalResult = result.ToList();

            OnPortsScanComplete(finalResult);
            return(finalResult);
        }
        public JObject WaitForSignal(string signal, IEnumerable <string> expressions)
        {
            var     timeout = 240;
            JObject result  = null;

            while (timeout > 0)
            {
                var findSignal = collectionOfSignal.FirstOrDefault(s => find(s, expressions));

                if (findSignal != null)
                {
                    return(findSignal);
                }
                Thread.Sleep(1000);
                timeout--;
            }
            return(result);
        }
Beispiel #18
0
        private async Task OnBeforeRequest(object sender, SessionEventArgs e)
        {
            if (e.WebSession == null || e.WebSession.Request == null)
            {
                return;
            }

            var importer = importers.FirstOrDefault(x => !x.IsDisabled() && x.IsRunning && x.IsMatch(e.WebSession.Request));

            if (importer == null)
            {
                return;
            }

            // remove compression
            e.WebSession.Request.Headers.RemoveHeader("Sec-WebSocket-Extensions");

            await Task.Run(() =>
            {
                e.DataReceived += (s, a) =>
                {
                    if (a.Count == 0)
                    {
                        return;
                    }

                    var capturedPacket = new CapturedPacket
                    {
                        Bytes            = a.Buffer.Take(a.Count).ToArray(),
                        CreatedTimeStamp = DateTime.UtcNow,
                        Source           = new IPEndPoint(IPAddress.Any, e.WebSession.Request.RequestUri.Port),
                        Destination      = e.ClientEndPoint
                    };

                    importer.AddPacket(capturedPacket);
                };
            });
        }
Beispiel #19
0
        /// <summary>
        /// Parses captured data into the packet
        /// </summary>
        /// <param name="rawCapture">Captured data</param>
        protected void ParsePacket(RawCapture rawCapture)
        {
            var packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);

            var tcpPacket = packet.Extract <TcpPacket>();
            var ipPacket  = packet.Extract <IpPacket>();

            if (tcpPacket == null || ipPacket == null)
            {
                return;
            }

            var matchedImporter = importers.FirstOrDefault(x => x.IsRunning && x.Match(tcpPacket, ipPacket));

            if (matchedImporter == null)
            {
                return;
            }

            var payloadData = tcpPacket.PayloadData;

            if (payloadData == null || payloadData.Length == 0)
            {
                return;
            }

            var capturedPacket = new CapturedPacket
            {
                Bytes            = tcpPacket.PayloadData,
                Source           = new IPEndPoint(ipPacket.SourceAddress, tcpPacket.SourcePort),
                Destination      = new IPEndPoint(ipPacket.DestinationAddress, tcpPacket.DestinationPort),
                CreatedTimeStamp = rawCapture.Timeval.Date,
                SequenceNumber   = tcpPacket.SequenceNumber
            };

            matchedImporter.AddPacket(capturedPacket);
        }
        protected override List <ReportIndicators> CombineChunkedIndicators(BlockingCollection <ReportIndicators> chunkedIndicators, CancellationToken cancellationToken)
        {
            var report = chunkedIndicators.FirstOrDefault();

            if (report == null)
            {
                return(new List <ReportIndicators>());
            }

            chunkedIndicators.Skip(1).ForEach(r =>
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                report.AddIndicator(r);
            });

            return(new List <ReportIndicators>
            {
                report
            });
        }
        /// <inheritdoc />
        public async void ChunkReceived(Command cmd, string streamId, string token, Metadata header)
        {
            try
            {
                if (cmd.Data.FirstOrDefault().TypeUrl == Any.Pack(new FileChunk()).TypeUrl)
                {
                    var chunk = cmd.Data.FirstOrDefault().CastToModel <FileChunk>();
                    if (fileChunkDictionary.ContainsKey(chunk.FileId))
                    {
                        while (!fileChunkDictionary[chunk.FileId].TryAdd(chunk))
                        {
                            await Task.Delay(1);
                        }
                        File file = fileList.FirstOrDefault(p => p.Id == chunk.FileId);
                        Console.WriteLine(file.TotalChunks + "/" + fileChunkDictionary[file.Id].Count);
                        if (file.TotalChunks == fileChunkDictionary[file.Id].Count)
                        {
                            Command completeFile = new Command()
                            {
                                Type  = CommandType.File,
                                Topic = StaticCommandKeys.FileTransfer
                            };

                            //stick together file
                            byte[] stickedFile = new byte[file.Size];
                            int    chunksize   = -1;
                            foreach (FileChunk c in fileChunkDictionary[file.Id].OrderBy(p => p.Index))
                            {
                                byte[] content = c.Content.ToArray();
                                if (chunksize == -1)
                                {
                                    chunksize = content.Length;
                                }
                                content.CopyTo(stickedFile, chunksize * c.Index);
                                content = null; // free up space in memory
                            }
                            file.Content = ByteString.CopyFrom(stickedFile);

                            //clear memory
                            stickedFile = null;

                            BlockingCollection <FileChunk> dump;
                            fileChunkDictionary.TryRemove(file.Id, out dump);
                            dump.Dispose();

                            //forward/send file as a complete package wrapped by a command
                            completeFile.Data.Add(Any.Pack(file));
                            FileReceived?.Invoke(completeFile, streamId, token, header);
                            completeFile = null; // free up space in memory
                            file         = null; // free up space in memory
                        }
                    }
                    else
                    {
                        new Task(async() =>
                        {
                            await new Func <bool>(() => fileChunkDictionary.ContainsKey(chunk.FileId)).AwaitResult(60);
                            ChunkReceived(cmd, streamId, token, header);
                        }).Start();
                    }
                }
                else
                {
                    // File information received
                    File file = cmd.Data.FirstOrDefault().CastToModel <File>();
                    while (!fileList.TryAdd(file))
                    {
                        await Task.Delay(1);
                    }

                    if (!fileChunkDictionary.ContainsKey(file.Id))
                    {
                        while (!fileChunkDictionary.TryAdd(file.Id, new BlockingCollection <FileChunk>()))
                        {
                            await Task.Delay(1);
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
        }
Beispiel #22
0
 internal static Mapper FindMapper(Type from, Type to)
 => converters.FirstOrDefault(d => d.Matches(from, to));
Beispiel #23
0
        private static int Main(string[] args)
        {
            var recursiveFlag    = SearchOption.TopDirectoryOnly;
            var enableCrossCheck = false;
            var rootFolder       = "";

            foreach (var argument in args)
            {
                if (argument == "-r" || argument == "/r")
                {
                    recursiveFlag = SearchOption.AllDirectories;
                }
                else if (argument == "-c" || argument == "/c")
                {
                    enableCrossCheck = true;
                }
                else if (argument == "-v" || argument == "/v")
                {
                    _verbose = true;
                }
                else if (string.IsNullOrEmpty(rootFolder))
                {
                    rootFolder = argument;
                }
            }

            if (string.IsNullOrEmpty(rootFolder))
            {
                Console.WriteLine("No root folder specified.");
                Console.WriteLine(HelpString);
                return((int)ErrorLevel.MissingRootFolder);
            }

            const string configFileType = "*.config";

            string[] dllFileType = { "*.exe", "*.dll" };
            string[] filesList;

            var outdatedList = new List <ReportItem>();

            //check .config file references
            try
            {
                filesList = Directory.GetFiles(rootFolder, configFileType, recursiveFlag);
            }
            catch (Exception e)
            {
                Console.WriteLine("File search exception: "
                                  + e
                                  + Environment.NewLine
                                  + "Possibly a file system link found.");
                return((int)ErrorLevel.FileSearchError);
            }

            var domain = new AssemblyDomain();

            Parallel.ForEach(filesList, fromFile =>
            {
                var config = new XmlDocument();

                try
                {
                    config.Load(fromFile);
                }
                catch
                {
                    // not XML file, skip it
                    return;
                }

                var assemblyNodes = config.GetElementsByTagName("dependentAssembly");
                if (assemblyNodes.Count <= 0)
                {
                    // no assembly references, skip it
                    return;
                }

                // process each assembly reference in the .config file
                foreach (XmlNode node in assemblyNodes)
                {
                    // get assembly name from config
                    var dllFileNode = node["assemblyIdentity"];
                    if (dllFileNode == null)
                    {
                        // no DLL name fixed in XML, skip it
                        continue;
                    }

                    var dllFileName = "";
                    foreach (XmlAttribute attribute in dllFileNode.Attributes)
                    {
                        if (attribute.Name == "name")
                        {
                            // DLL name tag found in XML
                            dllFileName = attribute.Value;
                            break;
                        }
                    }

                    if (string.IsNullOrEmpty(dllFileName))
                    {
                        // DLL name tag not found in XML, skip it
                        continue;
                    }

                    // get assembly version from config
                    var dllVersionNode = node["bindingRedirect"];
                    if (dllVersionNode == null)
                    {
                        // no DLL version tag found in XML
                        continue;
                    }

                    Version expectedVersion = null;
                    foreach (XmlAttribute attribute in dllVersionNode.Attributes)
                    {
                        if (attribute.Name == "newVersion")
                        {
                            try
                            {
                                expectedVersion = new Version(attribute.Value);
                            }
                            catch
                            {
                            }

                            // DLL version tag found in XML
                            break;
                        }
                    }

                    if (expectedVersion == null)
                    {
                        // DLL version tag not found in XML, skip it
                        continue;
                    }

                    // Get file version.
                    var dllFullFileName = FilePath(fromFile) + dllFileName + ".dll";
                    Version dllVersion;
                    try
                    {
                        dllVersion = AssemblyName.GetAssemblyName(dllFullFileName).Version;
                    }
                    catch
                    {
                        // no such DLL in the folder or error opening it
                        //Console.WriteLine("Can't open file: " + dllPath);
                        continue;
                    }

                    if (dllVersion == null)
                    {
                        // can't get file version, skip it
                        continue;
                    }

                    if (dllVersion < expectedVersion)
                    {
                        var fromFileItem = new FileItem(fromFile, expectedVersion);

                        var rptList = outdatedList.FindAll(x => x.AssemblyFile.FullFileName == dllFullFileName);
                        if (rptList.Count > 1)
                        {
                            Console.WriteLine("Duplicate assembly name in collection: " + dllFullFileName);
                        }

                        if (rptList.Count <= 0)
                        {
                            var rpt = new ReportItem(dllFullFileName, dllVersion);
                            rpt.CalledFromFiles.Add(fromFileItem);
                            outdatedList.Add(rpt);
                        }
                        else if (rptList.Count == 1)
                        {
                            rptList[0].CalledFromFiles.Add(fromFileItem);
                        }
                    }
                }
            });

            // collect folder assembly collection
            var assemblyList = new BlockingCollection <AssemblyInfoItem>();

            foreach (var fileType in dllFileType)
            {
                try
                {
                    filesList = Directory.GetFiles(rootFolder, fileType, recursiveFlag);
                }
                catch (Exception e)
                {
                    Console.WriteLine("File search exception: "
                                      + e
                                      + Environment.NewLine
                                      + "Possibly a file system link found.");
                    return((int)ErrorLevel.FileSearchError);
                }

                var fileNum = filesList.Length;
                foreach (var file in filesList)
                {
                    var newAssembly = domain.GetAssemblyInfo(file);
                    assemblyList.Add(newAssembly);
                    fileNum--;
                }
            }
            domain.Unload();

            var crossList = new List <CrossReportItem>();

            // check references for files grouped by folder
            while (true)
            {
                var activeFiles = assemblyList.Where(x => !x.Processed);
                if (activeFiles == null || !activeFiles.Any())
                {
                    break;
                }

                var currentPath = activeFiles.First().FilePath;
                var folderFiles = assemblyList.Where(x => x.FilePath == currentPath);
                foreach (var srcDllFile in folderFiles)
                {
                    srcDllFile.Processed = true;

                    //check cross-references for different versions
                    if (enableCrossCheck)
                    {
                        var verList = new CrossReportItem(srcDllFile.FullFileName, srcDllFile.FileVersion);
                        foreach (var refFromFile in folderFiles)
                        {
                            if (srcDllFile.FileName == refFromFile.FileName)
                            {
                                continue;
                            }

                            foreach (var referenceItem in refFromFile.ReferenceList)
                            {
                                if (referenceItem.FullFileName == srcDllFile.FileName)
                                {
                                    if (!verList.CalledFromFiles.ContainsKey(referenceItem.FileVersion))
                                    {
                                        verList.CalledFromFiles.Add(referenceItem.FileVersion, refFromFile.FileName);
                                    }
                                }
                            }
                        }

                        if (verList.CalledFromFiles.Count > 1)
                        {
                            crossList.Add(verList);
                        }
                    }

                    if (srcDllFile.ReferenceList == null || srcDllFile.ReferenceList.Count <= 0)
                    {
                        continue;
                    }

                    // check for files with version other than required by caller
                    foreach (var refFile in srcDllFile.ReferenceList)
                    {
                        var foundFiles = folderFiles.Where(x => x.FileName == refFile.FileName);
                        if (foundFiles.Any())
                        {
                            if (foundFiles.Count() > 1)
                            {
                                Console.WriteLine("Duplicate assembly name in collection: " + refFile.FileName);
                            }

                            var element = foundFiles.First();
                            if (element.FileVersion < refFile.FileVersion)
                            {
                                var fromFileItem = new FileItem(srcDllFile.FullFileName, refFile.FileVersion);

                                var rptList = outdatedList.Where(x => x.AssemblyFile.FullFileName == element.FullFileName);
                                if (!rptList.Any())
                                {
                                    var rpt = new ReportItem(element.FullFileName, element.FileVersion);
                                    rpt.CalledFromFiles.Add(fromFileItem);
                                    outdatedList.Add(rpt);
                                }
                                else
                                {
                                    rptList.First().CalledFromFiles.Add(fromFileItem);
                                }
                            }
                        }
                    }
                }
            }

            var errorLevel = ErrorLevel.NoError;

            // generate report to console
            if (crossList.Any())
            {
                Console.WriteLine("Assembly files reference check:");
                errorLevel = ErrorLevel.MultiReference;
                foreach (var reportItem in crossList)
                {
                    Console.WriteLine(reportItem.AssemblyFile + "[" + reportItem.AssemblyFileVersion + "] cross-referenced by:");
                    foreach (var fileItem in reportItem.CalledFromFiles)
                    {
                        Console.WriteLine("\tv."
                                          + fileItem.Key
                                          + " expected by "
                                          + fileItem.Value);
                    }
                }
            }

            // generate batch file to get correct files if any
            if (outdatedList.Count > 0)
            {
                Console.WriteLine("Assembly files reference check:");
                errorLevel = ErrorLevel.RecoverableErrors;
                var currentDir  = "";
                var copyCommand = new StringBuilder();
                foreach (var report in outdatedList)
                {
                    if (report.AssemblyFile.FilePath != currentDir)
                    {
                        currentDir = report.AssemblyFile.FilePath;
                        Console.WriteLine(currentDir + ":");
                    }

                    Console.WriteLine("\t"
                                      + report.AssemblyFile.FileName
                                      + " v."
                                      + report.AssemblyFile.FileVersion
                                      + " outdated");

                    foreach (var refFile in report.CalledFromFiles)
                    {
                        Console.WriteLine("\t\tv."
                                          + refFile.FileVersion
                                          + " expected by "
                                          + refFile.FileName);

                        var correctFile = assemblyList.FirstOrDefault(x => x.FileName == report.AssemblyFile.FileName && x.FileVersion == refFile.FileVersion);
                        if (correctFile != null)
                        {
                            copyCommand.AppendLine("rem v." + correctFile.FileVersion + " => " + report.AssemblyFile.FileVersion);
                            copyCommand.AppendLine("copy " + correctFile.FullFileName + " " + report.AssemblyFile.FullFileName);
                        }
                        else
                        {
                            copyCommand.AppendLine("rem v." + refFile.FileVersion + " => " + report.AssemblyFile.FileVersion);
                            copyCommand.AppendLine("rem copy " + "_from_repository_" + " " + report.AssemblyFile.FullFileName);
                            errorLevel = ErrorLevel.UnRecoverableErrors;
                        }
                    }
                }

                if (copyCommand.Length > 0)
                {
                    File.WriteAllText("fix.bat", copyCommand.ToString());
                }
            }

            return((int)errorLevel);
        }
        public void ApplyLoadToTheStorageMirrorTest()
        {
            #region ARRANGE

            PerformanceCounter         counterCPU;
            PerformanceCounter         counterRAM;
            BlockingCollection <float> metricsCPU;
            BlockingCollection <float> metricsRAM;

            counterCPU = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            counterRAM = new PerformanceCounter("Memory", "Available MBytes");
            metricsCPU = new BlockingCollection <float>(100000);
            metricsRAM = new BlockingCollection <float>(100000);

            Timer timerCPU;
            timerCPU = new Timer((state) =>
            {
                if (metricsCPU.IsAddingCompleted)
                {
                    float oldest = metricsCPU.FirstOrDefault();
                    metricsCPU.TryTake(out oldest);
                }
                metricsCPU.TryAdd(counterCPU.NextValue());
            }, null, 1000, 10);

            Timer timerRAM;
            timerRAM = new Timer((state) =>
            {
                if (metricsRAM.IsAddingCompleted)
                {
                    float oldest = metricsRAM.FirstOrDefault();
                    metricsRAM.TryTake(out oldest);
                }
                metricsRAM.TryAdd(counterRAM.NextValue());
            }, null, 1000, 10);

            counterCPU.NextValue();
            var memoryBefore = counterRAM.NextValue();
            Thread.Sleep(1000); // Per MSDN suggestion when using PerformanceCounter mechanism...

            int            totalCandidates = 1000000;
            int            countCallbacks  = 0;
            var            random          = new Random();
            var            data            = Enumerable.Range(1, totalCandidates).OrderBy(i => random.Next(1, totalCandidates));
            CountdownEvent countdown       = new CountdownEvent(totalCandidates);
            TheStorageMirror <TheStorageEngineTSM> mirror;
            mirror = new TheStorageMirror <TheStorageEngineTSM>(TheCDEngines.MyIStorageService)
            {
                IsRAMStore               = true,
                CacheStoreInterval       = 1,
                IsStoreIntervalInSeconds = true,
                IsCachePersistent        = true,
                UseSafeSave              = true,
                AllowFireUpdates         = true,
            };



            #endregion

            #region ACT

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            try
            {
                Parallel.ForEach(data, currentNumber =>
                {
                    mirror.AddAnItem(
                        new TheStorageEngineTSM()
                    {
                        TXTPattern = currentNumber.ToString()
                    },
                        state =>
                    {
                        Interlocked.Increment(ref countCallbacks);
                        countdown.Signal();
                    });
                });
            }
            catch (Exception ex)
            {
                Assert.IsTrue(true, ex.Message);
            }

            countdown.Wait();

            stopwatch.Stop();
            timerCPU.Change(Timeout.Infinite, Timeout.Infinite);
            timerCPU.Dispose();
            timerRAM.Change(Timeout.Infinite, Timeout.Infinite);
            timerRAM.Dispose();
            counterCPU?.Dispose();
            counterRAM?.Dispose();
            countdown?.Dispose();
            mirror?.Dispose();

            #endregion

            #region ASSERT

            float avgCPU = metricsCPU.Average();
            float maxCPU = 99f;

            float avgRAM = metricsRAM.Average();
            float maxRAM = memoryBefore + 1000f;

            Assert.IsTrue(
                (avgCPU <= maxCPU && avgRAM <= maxRAM && totalCandidates == countCallbacks),
                buildSummary(totalCandidates,
                             stopwatch.ElapsedMilliseconds,
                             avgCPU,
                             maxCPU,
                             avgRAM,
                             maxRAM));

            #endregion
        }
 public bool RemoveTest()
 {
     BlockingCollection<Security> dataQueue = new BlockingCollection<Security>();
     var sec1 = new Security("Aggregator", "AAA", 6.32D);
     var sec2 = new Security("Aggregator", "BBB", 6.22D);
     var sec3 = new Security("Aggregator", "CCC", 6.12D);
     dataQueue.Add(sec1);
     dataQueue.Add(sec2);
     dataQueue.Add(sec3);
     Assert.IsTrue(dataQueue.Remove<Security>(sec1));
     Assert.IsTrue(dataQueue.Count == 2);
     var itm = dataQueue.FirstOrDefault(x => x.Value == sec1.Value);
     return (null == itm);
 }
Beispiel #26
0
 private LandingPosition GetReservedLandingPositionAt(int x, int y)
 {
     return(landingPositions.FirstOrDefault(landingPosition => landingPosition.IsLocatedOn(x, y)));
 }
Beispiel #27
0
 public bool Exists(WebClient entity) => clients.FirstOrDefault(x => x.Id.Equals(entity.Id)) != null;
Beispiel #28
0
 public WebSocket GetSocketById(string id)
 {
     return(_sockets.FirstOrDefault(p => p.SocketId == id).Socket);
 }
Beispiel #29
0
 public WebClient GetByIp(string ip)
 {
     return(clients.FirstOrDefault(x => x.Ip.Equals(ip)));
 }
Beispiel #30
0
        public void CompareOdd2(List <MatchOddDTO> dataUpdated, BlockingCollection <MatchDTO> targetSource, bool isLive)
        {
            //TransactionDTO transaction = new TransactionDTO>();

            foreach (var data in dataUpdated)
            {
                if (!DataContainer.LeaguesDenyKeywords.Any(data.LeagueName.ToUpper().Contains) &&
                    (!DataContainer.MatchsDenyKeywords.Any(data.HomeTeamName.ToUpper().Contains) ||
                     !DataContainer.MatchsDenyKeywords.Any(data.AwayTeamName.ToUpper().Contains)))
                {
                    MatchDTO ibetMatchTarget = targetSource.FirstOrDefault(m =>
                                                                           (String.Equals(m.HomeTeamName, data.HomeTeamName,
                                                                                          StringComparison.CurrentCultureIgnoreCase)
                                                                            ||
                                                                            String.Equals(m.AwayTeamName, data.AwayTeamName,
                                                                                          StringComparison.CurrentCultureIgnoreCase)) &&
                                                                           !DataContainer.LeaguesDenyKeywords.Any(m.LeagueName.ToUpper().Contains));

                    if (ibetMatchTarget != null)
                    {
                        var ibetOdd = ibetMatchTarget.Odds.FirstOrDefault(o => o.Odd.Equals(data.Odd) &&
                                                                          o.OddType.Equals(data.OddType));

                        if (ibetOdd != null)
                        {
                            string oddCheck = ibetOdd.OddID + ibetOdd.HomeOdd + ibetOdd.AwayOdd +
                                              data.Odd + ibetOdd.Odd + data.HomeOdd + data.AwayOdd;

                            if (oddCheck.Equals(LastOddIdCheck))
                            {
                                continue;
                            }

                            if (IsValidOddPair(data.AwayOdd, ibetOdd.HomeOdd))
                            {
                                LastOddIdCheck = oddCheck;

                                BroadCastTransaction(new TransactionDTO
                                {
                                    IsLive       = isLive,
                                    SboMatchOdd  = data,
                                    SboBetType   = eBetType.Away,
                                    IbetBetType  = eBetType.Home,
                                    IbetMatchOdd = new MatchOddDTO(ibetMatchTarget.MatchID, ibetMatchTarget.LeagueName,
                                                                   ibetMatchTarget.HomeTeamName, ibetMatchTarget.AwayTeamName, ibetMatchTarget.TimeType, ibetMatchTarget.Minutes,
                                                                   ibetOdd.OddID, ibetOdd.Odd, ibetOdd.HomeOdd, ibetOdd.AwayOdd, ibetOdd.OddType)
                                }, oddCheck, 0);
                                break;
                            }

                            if (IsValidOddPair(data.HomeOdd, ibetOdd.AwayOdd))
                            {
                                LastOddIdCheck = oddCheck;
                                BroadCastTransaction(new TransactionDTO
                                {
                                    IsLive       = isLive,
                                    SboMatchOdd  = data,
                                    SboBetType   = eBetType.Home,
                                    IbetBetType  = eBetType.Away,
                                    IbetMatchOdd = new MatchOddDTO(ibetMatchTarget.MatchID, ibetMatchTarget.LeagueName,
                                                                   ibetMatchTarget.HomeTeamName, ibetMatchTarget.AwayTeamName, ibetMatchTarget.TimeType, ibetMatchTarget.Minutes,
                                                                   ibetOdd.OddID, ibetOdd.Odd, ibetOdd.HomeOdd, ibetOdd.AwayOdd, ibetOdd.OddType)
                                }, oddCheck, 0);

                                break;
                            }
                        }
                    }
                }
            }
        }
Beispiel #31
0
        private void SellCallBack(object obj)
        {
            BrokerTransaction tran = obj as BrokerTransaction;

            var checkMatchScored = ScoredMatchs.FirstOrDefault(m => (String.Equals(m.HomeTeamName, tran.BuyMatchOdd.HomeTeamName, StringComparison.CurrentCultureIgnoreCase) ||
                                                                     String.Equals(m.AwayTeamName, tran.BuyMatchOdd.AwayTeamName, StringComparison.CurrentCultureIgnoreCase)) &&
                                                               tran.SumScore != (m.HomeScore + m.AwayScore));

            if (checkMatchScored != null)
            {
                tran.FinishTransaction = true;
                tran.SellTimer.Dispose();
                return;
            }

            if (tran.SumMoneyBuy <= MaxPointCheck)
            {
                tran.FinishTransaction = true;
                tran.SellTimer.Dispose();
                return;
            }

            lock (LockBetSellEngine)
            {
                BetSellEngines.Shuffle();

                foreach (var sellEngine in BetSellEngines)
                {
                    if ((!tran.FastSell && sellEngine.ServerType != tran.ServerSell) ||
                        (tran.FastSell && tran.ServerSell != eServerType.Unknown && sellEngine.ServerType != tran.ServerSell))
                    {
                        continue;
                    }

                    if ((tran.ServerSell == eServerType.Ibet && sellEngine.EngineId == LastIbetEngineIdSell) ||
                        (tran.ServerSell == eServerType.Sbo && sellEngine.EngineId == LastSboEngineIdSell))
                    {
                        continue;
                    }

                    var sellPrepare = sellEngine.PrepareBetBroker(tran.BuyMatchOdd, tran.SellBetType, tran.BuyMatchOdd.Odd);
                    if (sellPrepare != null)
                    {
                        bool last      = (tran.SellSuccessCount + 1) >= tran.CountBuyEngine;
                        int  sellMoney = last ? tran.SumMoneyBuy : tran.SellMoneyAverage;

                        int sellPoint = ConvertMoneyToPoint(sellMoney, sellEngine.ExchangeRate);
                        if (sellPoint > sellPrepare.MaxBet)
                        {
                            sellPoint = sellPrepare.MaxBet;
                        }
                        sellPoint = GetGoodPoint(sellPoint, sellPrepare.MaxBet, true, last);

                        if (sellEngine.ConfirmBetBroker(sellPoint))
                        {
                            if (tran.ServerSell == eServerType.Ibet)
                            {
                                LastIbetEngineIdSell = sellEngine.EngineId;
                            }
                            else
                            {
                                LastSboEngineIdSell = sellEngine.EngineId;
                            }

                            tran.SumMoneyBuy -= ConvertPointToMoney(sellPoint, sellEngine.ExchangeRate);

                            if (tran.FastSell)
                            {
                                UpdateWriteTextLog(string.Format("BÁN NHANH [{6}] sau {8} phút  {0} vs {1} {2}:{3} PICK {4}: {5}  *stake: {7}",
                                                                 tran.BuyMatchOdd.HomeTeamName, tran.BuyMatchOdd.AwayTeamName,
                                                                 tran.BuyMatchOdd.OddType, tran.BuyMatchOdd.Odd, tran.SellBetType, sellPrepare.NewOdd, sellEngine.UserName, sellPoint, tran.TimeCheckScan), eLogTextType.Warning, eBrokerStatus.Sell);
                            }
                            else
                            {
                                UpdateWriteTextLog(string.Format("BÁN [{6}]: {0} vs {1} {2}:{3} PICK {4}: {5}  **stake: {7}",
                                                                 tran.BuyMatchOdd.HomeTeamName, tran.BuyMatchOdd.AwayTeamName,
                                                                 tran.BuyMatchOdd.OddType, tran.BuyMatchOdd.Odd, tran.SellBetType, sellPrepare.NewOdd, sellEngine.UserName, sellPoint), eLogTextType.Warning, eBrokerStatus.Sell);
                            }

                            tran.SellSuccessCount++;
                            if (tran.SumMoneyBuy <= MaxPointCheck)
                            {
                                tran.FinishTransaction = true;
                                tran.SellTimer.Dispose();
                                break;
                            }
                            else
                            {
                                tran.SellTimer.Change(WaitSellTimes[R.Next(WaitSellTimes.Count)], 60000);
                                break;
                            }
                        }
                    }
                }
            }
        }