private async Task ValidateAndSetDefaultsAsync()
        {
            //Check https://www.bricelam.net/2016/12/13/validation-in-efcore.html
            var entities = from e in ChangeTracker.Entries()
                           where e.State == EntityState.Added ||
                           e.State == EntityState.Modified
                           select e.Entity;
            string ipAddresses      = String.Empty;
            string assemblyFullName = String.Empty;
            string rowCretionUser   = String.Empty;

            if (entities.Any(p => p is IOriginatorInfo))
            {
                ipAddresses      = String.Join(",", await IpAddressProvider.GetCurrentHostIPv4AddressesAsync());
                assemblyFullName = System.Reflection.Assembly.GetEntryAssembly().FullName;
                rowCretionUser   = this.CurrentUserProvider.GetUsername();
            }
            foreach (var entity in entities)
            {
                if (entity is IOriginatorInfo)
                {
                    IOriginatorInfo entityWithOriginator = entity as IOriginatorInfo;
                    if (String.IsNullOrWhiteSpace(entityWithOriginator.SourceApplication))
                    {
                        entityWithOriginator.SourceApplication = assemblyFullName;
                    }
                    if (String.IsNullOrWhiteSpace(entityWithOriginator.OriginatorIpaddress))
                    {
                        entityWithOriginator.OriginatorIpaddress = ipAddresses;
                    }
                    if (entityWithOriginator.RowCreationDateTime == DateTimeOffset.MinValue)
                    {
                        entityWithOriginator.RowCreationDateTime = DateTimeOffset.UtcNow;
                    }
                    if (String.IsNullOrWhiteSpace(entityWithOriginator.RowCreationUser))
                    {
                        entityWithOriginator.RowCreationUser = rowCretionUser;
                    }
                }
                var validationContext = new ValidationContext(entity);
                Validator.ValidateObject(
                    entity,
                    validationContext,
                    validateAllProperties: true);
            }
        }
Exemple #2
0
        public static void Main(string[] args)
        {
            var ipAddress        = IpAddressProvider.GetLocalIpAddress();
            var registrarService = new RegistrarService();
            var server           = new Server
            {
                Services = { Protocol.Registrar.BindService(registrarService) },
                Ports    = { new ServerPort(ipAddress, Port, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine("Registrar listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
        public async Task <VisitorTracking> TrackVisitAsync(VisitorTrackingModel visitorTrackingModel)
        {
            try
            {
                var httpContext     = HttpContextAccessor.HttpContext;
                var remoteIpAddress = httpContext.Connection.RemoteIpAddress.ToString();
                if (remoteIpAddress == "::1")
                {
                    var ipAddresses = await IpAddressProvider.GetCurrentHostIPv4AddressesAsync();

                    remoteIpAddress = ipAddresses.First();
                }
                var parsedIpAddress   = System.Net.IPAddress.Parse(remoteIpAddress);
                var ipGeoLocationInfo = await IpDataService.GetIpGeoLocationInfoAsync(ipAddress : parsedIpAddress);

                //var ipGeoLocationInfo = await IpStackService.GetIpGeoLocationInfoAsync(ipAddress: parsedIpAddress);
                string          country    = ipGeoLocationInfo.country_name;
                var             host       = httpContext.Request.Host.Value;
                var             userAgent  = httpContext.Request.Headers["User-Agent"].First();
                ApplicationUser userEntity = null;
                if (!String.IsNullOrWhiteSpace(visitorTrackingModel.UserAzureAdB2cObjectId))
                {
                    userEntity = await this.FairplaytubeDatabaseContext.ApplicationUser.SingleOrDefaultAsync(p => p.AzureAdB2cobjectId.ToString() == visitorTrackingModel.UserAzureAdB2cObjectId);
                }
                var visitedPage = new DataAccess.Models.VisitorTracking()
                {
                    ApplicationUserId = userEntity?.ApplicationUserId,
                    Country           = country,
                    Host            = host,
                    RemoteIpAddress = remoteIpAddress,
                    UserAgent       = userAgent,
                    VisitDateTime   = DateTimeOffset.UtcNow,
                    VisitedUrl      = visitorTrackingModel.VisitedUrl,
                    SessionId       = visitorTrackingModel.SessionId
                };
                await this.FairplaytubeDatabaseContext.VisitorTracking.AddAsync(visitedPage);

                await this.FairplaytubeDatabaseContext.SaveChangesAsync();

                var pageUri     = new Uri(visitedPage.VisitedUrl);
                var lastSegment = pageUri.Segments.Last().TrimEnd('/');
                if (!String.IsNullOrWhiteSpace(lastSegment))
                {
                    var videoInfoEntity = await this.FairplaytubeDatabaseContext.VideoInfo.SingleOrDefaultAsync(p => p.VideoId == lastSegment);

                    if (videoInfoEntity != null)
                    {
                        visitedPage.VideoInfoId = videoInfoEntity.VideoInfoId;
                        await this.FairplaytubeDatabaseContext.SaveChangesAsync();
                    }
                }
                return(visitedPage);
            }
            catch (Exception ex)
            {
                try
                {
                    await this.FairplaytubeDatabaseContext.ErrorLog.AddAsync(new ErrorLog()
                    {
                        FullException = ex.ToString(),
                        Message       = ex.Message,
                        StackTrace    = ex.StackTrace
                    });

                    await this.FairplaytubeDatabaseContext.SaveChangesAsync();
                }
                catch (Exception)
                {
                    throw;
                }
            }
            return(null);
        }
Exemple #4
0
        public static void Main(string[] args)
        {
            var configFilepath = args[0];
            var password       = args[1];

            // config
            var nodeConfig      = ConfigDeserializer.Deserialize <NodeConfig>(configFilepath);
            var console         = ConsoleFactory.Build(nodeConfig.IsMiningNode);
            var ipAddress       = IpAddressProvider.GetLocalIpAddress();
            var electionEndTime = nodeConfig.IsClassDemo ? DateTime.Now.AddSeconds(120) : nodeConfig.ElectionEndTime;

            // password check
            var voterDb    = new VoterDatabaseFacade(nodeConfig.VoterDbFilepath);
            var foundMiner = voterDb.TryGetVoterEncryptedKeyPair(password, out var encryptedKeyPair);

            if (!foundMiner)
            {
                Console.WriteLine("incorrect password: you may not mine!");
                return;
            }

            // blockchain
            var blockchain = new Blockchain();

            // networking
            var registrarClientFactory     = new RegistrarClientFactory();
            var registrarClient            = registrarClientFactory.Build(ipAddress, RegistrarPort);
            var registrationRequestFactory = new RegistrationRequestFactory();
            var myConnectionInfo           = new NodeConnectionInfo(ipAddress, nodeConfig.Port);
            var knownNodeStore             = new KnownNodeStore();
            var nodeClientFactory          = new NodeClientFactory();
            var handshakeRequestFactory    = new HandshakeRequestFactory(blockchain);
            var nodeClientStore            = new NodeClientStore();
            var nodeServerFactory          = new NodeServerFactory();

            // votes
            var protoVoteFactory = new ProtoVoteFactory();
            var voteForwarder    = new VoteForwarder(nodeClientStore, protoVoteFactory);
            var voteMemoryPool   = new VoteMemoryPool(voteForwarder, console);

            // blocks
            var merkleNodeFactory = new MerkleNodeFactory();
            var merkleTreeFactory = new MerkleTreeFactory(merkleNodeFactory);
            var minerId           = encryptedKeyPair.PublicKey.GetBase64String();
            var blockFactory      = new BlockFactory(merkleTreeFactory, minerId);
            var protoBlockFactory = new ProtoBlockFactory(protoVoteFactory);
            var blockForwarder    = new BlockForwarder(nodeClientStore, protoBlockFactory);
            var voteValidator     = new VoteValidator(blockchain, voterDb, electionEndTime);
            var blockValidator    = new BlockValidator(blockFactory, voteValidator);
            var blockchainAdder   = new BlockchainAdder(blockchain, voteMemoryPool, blockForwarder, console);

            // mining
            var difficultyTarget = TargetFactory.Build(BlockHeader.DefaultBits);
            var miner            = new Miner(
                blockchain,
                voteMemoryPool,
                difficultyTarget,
                blockFactory,
                blockchainAdder,
                console);

            // interaction
            var voteSerializer           = new VoteSerializer();
            var electionAlgorithmFactory = new ElectionAlgorithmFactory(voteSerializer);
            var electionAlgorithm        = electionAlgorithmFactory.Build(nodeConfig.ElectionType);
            var electionResultProvider   = new ElectionResultProvider(
                electionAlgorithm,
                electionEndTime,
                voteMemoryPool,
                blockchain);
            var voterTerminal = new VoterTerminal.VoterTerminal(
                voterDb,
                nodeConfig.Candidates.ToArray(),
                voteSerializer,
                voteMemoryPool,
                electionResultProvider,
                blockchain);
            var votingBooth = new VoterTerminal.VoterBooth(voterTerminal, nodeConfig.ElectionType);

            // startup
            var nodeServer = nodeServerFactory.Build(
                myConnectionInfo,
                knownNodeStore,
                nodeClientFactory,
                nodeClientStore,
                voteMemoryPool,
                blockchain,
                miner,
                voteValidator,
                blockValidator,
                blockchainAdder,
                console);
            var boostrapper = new Bootstrapper(
                MinNetworkSize,
                knownNodeStore,
                nodeClientFactory,
                handshakeRequestFactory,
                nodeClientStore,
                registrarClient,
                registrationRequestFactory,
                nodeServer);

            Console.WriteLine("bootstrapping node network...");
            boostrapper.Bootstrap(myConnectionInfo);
            Console.WriteLine($"{MinNetworkSize} nodes in network! bootstrapping complete");

            if (nodeConfig.IsMiningNode)
            {
                Console.WriteLine("starting miner...");
                miner.Start();

                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Press any key to quit");
                Console.ReadKey();
            }
            else
            {
                votingBooth.LaunchBooth();
            }
        }