示例#1
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                // Address Enrollments Client Side Stream
                var userAddress = new AddAddressRequest
                {
                    StudentId   = Guid.NewGuid().ToString(), /* To Be replaced with Students's Id*/
                    Name        = NameGenerator.GenerateName(12),
                    FullAddress = AddressGenerator.GenerateAddress(),
                    Enrollment  = Konstants.AddressConstants.EnrollmentTypes[RandomNumberGenerator.GetRandomValue(1, 4)]
                };

                using (var stream = _addressClient.AddAddressEnrollments())
                {
                    foreach (string enrollmentType in Konstants.AddressConstants.EnrollmentTypes)
                    {
                        userAddress.Enrollment = enrollmentType;
                        await stream.RequestStream.WriteAsync(userAddress);
                    }

                    await stream.RequestStream.CompleteAsync();

                    await stream;
                    WriteLine($"Sent All");
                }

                // await Task.Delay(1000, stoppingToken);
                await Task.Delay(_config.GetValue <int>("RPCService:DelayInterval"), stoppingToken);
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            // Create the tries
            var binaryRoot     = new BinaryNode("Root");
            var compressedRoot = new CompressedNode("Root");
            var multibitRoot   = new MultibitNode()
            {
                Stride = 3
            };

            // Generate IPs
            var gen = new AddressGenerator().GenerateAddress();
            var db  = gen.Take(10).ToArray();

            // Add children to tries
            foreach (var ip in db)
            {
                binaryRoot.AddChild(ip.MaskedIPv4, ip.BinaryString);
                compressedRoot.AddChild(ip.MaskedIPv4, ip.BinaryString);
                multibitRoot.AddChild(ip.MaskedIPv4, ip.BinaryString);
            }
            compressedRoot.Compress();

            // Perform a lookup
            var tosearch = new Address("132.15.162.33/17");

            Console.WriteLine($"Binary: {binaryRoot.Lookup(tosearch.BinaryString)}");
            Console.WriteLine($"Compressed: {compressedRoot.Lookup(tosearch.BinaryString)}");
            Console.WriteLine($"Multibit: {multibitRoot.Lookup(tosearch.BinaryString, "Root")}");

            Console.ReadLine();
        }
示例#3
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                var userAddress = new AddAddressRequest
                {
                    StudentId   = Guid.NewGuid().ToString(), /* To Be replaced with Students's Id*/
                    Name        = NameGenerator.GenerateName(12),
                    FullAddress = AddressGenerator.GenerateAddress(),
                    Enrollment  = Constants.AddressConstants.EnrollmentTypes[RandomNumberGenerator.GetRandomValue(1, 4)]
                };

                try
                {
                    var newAddress = await _client.AddAddressAsync(userAddress);

                    Console.WriteLine($"Address Data with Id: {newAddress.Id}");
                }
                catch (RpcException rpcError)
                {
                    _logger.LogError($"Error received from Server. {rpcError.Message} {rpcError.Trailers}");
                }

                await Task.Delay(_config.GetValue <int>("RPCService:DelayInterval"), stoppingToken);
            }
        }
示例#4
0
        public void generateAddressFromUser(User user, int start, int end)
        {
            var addressGenerator = new AddressGenerator(user.getSeed());

            int i;

            for (i = start; i < end; i++)
            {
                AddressTable addr = new AddressTable()
                {
                    Index            = user.AddressIndex + i,
                    generatedAddress = addressGenerator.GetAddress(user.AddressIndex + i).ToString(),
                    UserID           = user.UserID
                };

                _context.AddressTable.Add(addr);
            }

            user.AddressIndex += i;

            var entity = _context.User.Find(user.UserID);

            _context.Entry(entity).CurrentValues.SetValues(user);

            _context.SaveChanges();
        }
        protected override void Seed(BookingsDbContext context)
        {
            var random            = new Random();
            var addressGenerator  = new AddressGenerator();
            var userNameGenerator = new UserNameGenerator();
            var passportGenerator = new PassportGenerator();

            for (int i = 0; i < 60; i++)
            {
                var fromDate = DateTime.Today.AddDays(random.Next(-2, 5));
                var toDate   = fromDate.AddDays(random.Next(1, 5));

                context.Bookings.Add(new Booking
                {
                    CustomerId   = "Cust-10" + i,
                    CustomerName = userNameGenerator.GetName(),
                    Address      = addressGenerator.GetAddress(),
                    From         = fromDate,
                    To           = toDate,
                    Passport     = passportGenerator.GetPassport(),
                    Amount       = random.Next(10, 40) * 100
                });
            }

            context.SaveChanges();

            base.Seed(context);
        }
 public GasInjectorTests()
 {
     this.loggerFactory = new ExtendedLoggerFactory();
     this.loggerFactory.AddConsoleWithFilters();
     this.validator        = new SmartContractValidator();
     this.addressGenerator = new AddressGenerator();
 }
    public void TestSecurityLevelLowerThanDefault()
    {
      var generator = new AddressGenerator();

      var addresses = generator.GetAddresses(this.seedOne, SecurityLevel.Low, 0, 3);
      Assert.AreEqual("KNDWDEEWWFVZLISLYRABGVWZCHZNZLNSEJXFKVGAUFLL9UMZYEZMEJB9BDLAASWTHEKFREUDIUPY9ICKW", addresses[0].Value);
      Assert.AreEqual("CHOBTRTQWTMH9GWFWGWUODRSGPOJOIVJUNIQIBZLHSWNYPHOD9APWJBMJMGLHFZENWFKDYWHX9JDFXTAB", addresses[1].Value);
      Assert.AreEqual("YHTOYQUCLDHAIDILFNPITVPYSTOCFAZIUNDYTRDZCVMVGZPONPINNVPJTOAOKHHZWLOKIZPVASTOGAKPA", addresses[2].Value);
    }
    public void TestSecurityLevelHigherThanDefault()
    {
      var generator = new AddressGenerator();

      var addresses = generator.GetAddresses(this.seedOne, SecurityLevel.High, 0, 3);
      Assert.AreEqual("BGHTGOUKKNTYFHYUAAPSRUEVN9QQXFOGVCH9Y9BONWXUBDLSKAWEOFZIVMHXBAYVPGDZEYCKNTUJCLPAX", addresses[0].Value);
      Assert.AreEqual("EGMRJEUIYFUGWAIXXZCHCZUVUUYITICVHDSHCQXGFHJIVDCLTI9ZVRIKRLZQWW9CPOIXVDCBAHVGLUHI9", addresses[1].Value);
      Assert.AreEqual("ENPSARVJZGMMPWZTAIRHADEOZCEVIFNJWSZQHNEIRVEVI9GYMFNEOGNUYCPGPSEFCSDHUHOQKDPVGDKYC", addresses[2].Value);
    }
 public SmartContractExceptionTests()
 {
     this.repository          = new ContractStateRepositoryRoot(new NoDeleteSource <byte[], byte[]>(new MemoryDictionarySource()));
     this.keyEncodingStrategy = BasicKeyEncodingStrategy.Default;
     this.loggerFactory       = new ExtendedLoggerFactory();
     this.loggerFactory.AddConsoleWithFilters();
     this.network          = new SmartContractsRegTest();
     this.validator        = new SmartContractValidator();
     this.addressGenerator = new AddressGenerator();
 }
示例#10
0
        public void ShouldGenerateAddressesFromPrivateKey(string privateKey, string address)
        {
            var privKeyStr = Encoders.Hex.DecodeData(privateKey);
            Key key        = new Key(privKeyStr);

            IAddressGenerator addressGenerator = new AddressGenerator();
            var actulaAddress = addressGenerator.GenerateAddress(key.PubKey.ToBytes());

            Assert.AreEqual(address, actulaAddress);
        }
示例#11
0
        public void ShouldGenerateAddressesFromPrivateKey(string privateKey, string address)
        {
            var privKeyStr = Encoders.Hex.DecodeData(privateKey);
            Key key        = new Key(privKeyStr);

            // Works for Mainnet by default when no wallet instance is created
            IAddressGenerator addressGenerator = new AddressGenerator();
            var actualAddress = addressGenerator.GenerateAddress(key.PubKey.ToBytes());

            Assert.AreEqual(address, actualAddress);
        }
    public void TestGetSingleAddress()
    {
      var generator = new AddressGenerator();

      var address = generator.GetAddress(this.seedOne, SecurityLevel.Medium, 0);
      Assert.AreEqual("DLEIS9XU9V9T9OURAKDUSQWBQEYFGJLRPRVEWKN9SSUGIHBEIPBPEWISSAURGTQKWKWNHXGCBQTWNOGIY", address.Value);
      Assert.AreEqual(2, address.SecurityLevel);

      var addressTwo = generator.GetAddress(this.seedOne, SecurityLevel.Medium, 10);
      Assert.AreEqual("XLXFTFBXUOOHRJDVBDBFEBDQDUKSLSOCLUYWGLAPR9FUROUHPFINIUFKYSRTFMNWKNEPDZATWXIVWJMDD", addressTwo.Value);
      Assert.AreEqual(10, addressTwo.KeyIndex);
    }
        private static void SendMessage()
        {
            var rnd     = new Random();
            var gender  = new string[] { "F", "M" }[rnd.Next(0, 2)];
            var address = AddressGenerator.Generate();

            var personEUCCID = new EUCCID()
            {
                ChristianName      = NameGenerator.GenerateFirstName(gender),
                FamilyName         = NameGenerator.GenerateSurname(),
                EuccidNo           = EuccidGenerator.Generate(new DateTime(1987, 4, 23)),
                Gender             = gender,
                StreetAndHouseNo   = string.Format($"{address.Street} {address.HouseNo}"),
                ApartmentNo        = address.ApartmentNo,
                PostalCode         = address.PostalCode,
                City               = address.City,
                CountryOfResidence = "Denmark"
            };

            Console.WriteLine("---------- EUCCID input: ----------");
            personEUCCID.PrintAll();

            // translate into CDM format
            var personCDM = EuccidTranslator.EuccidToCdm(personEUCCID);

            Console.WriteLine("\n---------- Translated into CDM: ----------");
            personCDM.PrintAll();

            // build message
            var message = new Message()
            {
                Body  = personCDM,
                Label = personCDM.ToString()
            };

            // build channel
            var path = @".\Private$\EUCCID_to_CPR";

            if (!MessageQueue.Exists(path))
            {
                MessageQueue.Create(path);
            }

            var euccidToCprChannel = new MessageQueue(path)
            {
                Label = "EU-CCID to CPR"
            };

            // send
            euccidToCprChannel.Send(message);

            Console.WriteLine("\n---------- Message sent. ----------\n\n");
        }
示例#14
0
        protected override void Seed(BookingsDbContext context)
        {
            var random               = new Random();
            var addressGenerator     = new AddressGenerator();
            var userNameGenerator    = new UserNameGenerator();
            var passportGenerator    = new PassportGenerator();
            var cultureCodeGenerator = new CultureGenerator();

            for (int i = 0; i < 8; i++)
            {
                var fromDate = DateTime.Today;
                var toDate   = fromDate.AddDays(random.Next(1, 5));

                context.Bookings.Add(new Booking
                {
                    CustomerId   = "Cust-10" + i,
                    CustomerName = userNameGenerator.GetName(),
                    Address      = addressGenerator.GetAddress(),
                    From         = fromDate,
                    To           = toDate,
                    Passport     = passportGenerator.GetPassport(),
                    Amount       = random.Next(10, 40) * 100,
                    Type         = "CheckIn",
                    Culture      = cultureCodeGenerator.Cultures[random.Next(0, cultureCodeGenerator.Cultures.Count - 1)]
                });
            }

            for (int i = 0; i < 8; i++)
            {
                var fromDate = DateTime.Today.AddDays(random.Next(-5, -2));
                var toDate   = DateTime.Today;

                context.Bookings.Add(new Booking
                {
                    CustomerId   = "Cust-10" + i,
                    CustomerName = userNameGenerator.GetName(),
                    Address      = addressGenerator.GetAddress(),
                    From         = fromDate,
                    To           = toDate,
                    Passport     = passportGenerator.GetPassport(),
                    Amount       = random.Next(10, 40) * 100,
                    Type         = "CheckOut",
                    Culture      = cultureCodeGenerator.Cultures[random.Next(0, cultureCodeGenerator.Cultures.Count - 1)]
                });
            }

            context.SaveChanges();

            base.Seed(context);
        }
        public ReflectionVirtualMachineTests()
        {
            this.network             = new SmartContractsRegTest();
            this.keyEncodingStrategy = BasicKeyEncodingStrategy.Default;
            this.loggerFactory       = new ExtendedLoggerFactory();
            this.loggerFactory.AddConsoleWithFilters();
            this.gasLimit = (Gas)10000;
            this.gasMeter = new GasMeter(this.gasLimit);

            this.state = new ContractStateRepositoryRoot(new NoDeleteSource <byte[], byte[]>(new MemoryDictionarySource()));
            var persistenceStrategy = new MeteredPersistenceStrategy(this.state, this.gasMeter, this.keyEncodingStrategy);

            this.persistentState  = new PersistentState(persistenceStrategy, TestAddress.ToUint160(this.network), this.network);
            this.addressGenerator = new AddressGenerator();
            this.validator        = new SmartContractValidator();
        }
示例#16
0
        private void AcceptButton_Click(object sender, RoutedEventArgs e)
        {
            if (minMask.Value > maxMask.Value)
            {
                MessageBox.Show("Max Mask is higher than Min Mask!");
            }

            if (minOctet1.Value > maxOctet1.Value)
            {
                MessageBox.Show("Max Octet1 is higher than Min Octet1!");
            }

            if (minOctet2.Value > maxOctet2.Value)
            {
                MessageBox.Show("Max Octet2 is higher than Min Octet2!");
            }

            if (minOctet3.Value > maxOctet3.Value)
            {
                MessageBox.Show("Max Octet3 is higher than Min Octet3!");
            }

            if (minOctet4.Value > maxOctet4.Value)
            {
                MessageBox.Show("Max Octet4 is higher than Min Octet4!");
            }

            var ips = new AddressGenerator()
                      .GenerateAddress(
                (int)minOctet1.Value, (int)maxOctet1.Value,
                (int)minOctet2.Value, (int)maxOctet2.Value,
                (int)minOctet3.Value, (int)maxOctet3.Value,
                (int)minOctet4.Value, (int)maxOctet4.Value,
                (int)minMask.Value, (int)maxMask.Value)
                      .Take((int)amount.Value);

            if (Target == LoadTarget.Database)
            {
                Globals.CreateDatabase(ips);
            }
            else
            {
                Globals.SetToSearch(ips);
            }

            Hide();
        }
    public void TestGetMultipleAddresses()
    {
      var generator = new AddressGenerator();

      var addresses = generator.GetAddresses(this.seedTwo, SecurityLevel.Medium, 1, 1);
      Assert.AreEqual(1, addresses.Count);

      addresses = generator.GetAddresses(this.seedTwo, SecurityLevel.Medium, 0, 3);
      Assert.AreEqual("FNKCVJPUANHNWNBAHFBTCONMCUBC9KCZ9EKREBCJAFMABCTEPLGGXDJXVGPXDCFOUCRBWFJFLEAVOEUPY", addresses[0].Value);
      Assert.IsNotNull(addresses[0].PrivateKey);
      Assert.AreEqual("MSYILYYZLSJ99TDMGQHDOBWGHTBARCBGJZE9PIMQLTEXJXKTDREGVTPA9NDGGLQHTMGISGRAKSLYPGWMB", addresses[1].Value);
      Assert.AreEqual("IIREHGHXUHARKVZDMHGUUCHZLUEQQULLEUSJHIIBWFYZIZDUFTOVHAWCKRJXUZ9CSUVLTRYSUGBVRMTOW", addresses[2].Value);
      Assert.AreEqual(3, addresses.Count);

      addresses = generator.GetAddresses(this.seedTwo, SecurityLevel.Medium, 10, 3);
      Assert.AreEqual("BPXMVV9UPKBTVPJXPBHHOJYAFLALOYCGTSEDLZBHNFMGEHREBQTRIPZAPREANPMZJNZZNCDIUFOYYGGFY", addresses[0].Value);
      Assert.AreEqual("RUCZQJWKXVDIXTLHHOKGMHOV9AKVDBG9HUQHPWNZUNKJNFVMULUSLKFJGSTBSNJMRYSJOBVBQSKVXISZB", addresses[1].Value);
      Assert.AreEqual("FQAKF9XVCLTBESJKWCHFOCTVABYEEJP9RXUVAEUWENFUUQK9VCHFEORHCYDUJQHNUDWNRDUDZTUGKHSPD", addresses[2].Value);
      Assert.AreEqual(3, addresses.Count);
    }
示例#18
0
        public async Task <User> UniquePublicKey()
        {
            var publicKeyList = await IotaHelper.GetPublicKeysAndContactAddresses(this.user.TangleMessenger, this.user.PublicKeyAddress, true);

            var requestAdressTrytes = new TryteString(this.user.NtruKeyPair.PublicKey.ToBytes().EncodeBytesAsString() + ChiotaConstants.LineBreak + this.user.RequestAddress + ChiotaConstants.End);

            // after a snapshot, upload public key again
            if (publicKeyList.Count == 0)
            {
                await this.user.TangleMessenger.SendMessageAsync(requestAdressTrytes, this.user.PublicKeyAddress);
            }
            else if (publicKeyList.Count > 1)
            {
                // more than one key at this address
                // generate a new public key address based on a changed seed until you find an unused address
                // this way the attacker doesn't know the next public key address
                List <Contact> newContacts;
                var            addresses = new List <Address> {
                    new Address(this.user.PublicKeyAddress)
                };
                do
                {
                    var newSeed          = this.user.Seed.ToString().Substring(0, 75) + addresses[0].ToString().Substring(0, 6);
                    var addressGenerator = new AddressGenerator(new Kerl(), new KeyGenerator(new Kerl(), new IssSigningHelper()));
                    addresses = await Task.Factory.StartNew(() => addressGenerator.GetAddresses(new Seed(newSeed), SecurityLevel.Medium, 0, 1));

                    // returns also null if something wrong with ntru key pair
                    newContacts = await IotaHelper.GetPublicKeysAndContactAddresses(this.user.TangleMessenger, addresses[0].ToString(), true);

                    if (newContacts == null || newContacts.Count == 0)
                    {
                        await this.user.TangleMessenger.SendMessageAsync(requestAdressTrytes, addresses[0].ToString());
                    }

                    this.user.PublicKeyAddress = addresses[0].ToString();
                }while (newContacts?.Count > 1);
            }

            return(this.user);
        }
示例#19
0
        static async Task Main(string[] args)
        {
            string response = "Y";

            _config = new ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json").Build();

            // gRPC Clients
            CollegeServiceClient    CollegeClient = CollegeServiceClientHelper.GetCollegeServiceClient(_config["RPCService:ServiceUrl"]);
            AddressBookServerClient AddressClient = AddressServiceClientHelper.GetAddressBookServerClient(_config["RPCService:ServiceUrl"]);

            // Address Enrollments Client Side Stream
            var userAddress = new AddAddressRequest
            {
                StudentId   = Guid.NewGuid().ToString(), /* To Be replaced with Students's Id*/
                Name        = NameGenerator.GenerateName(12),
                FullAddress = AddressGenerator.GenerateAddress(),
                Enrollment  = Konstants.AddressConstants.EnrollmentTypes[RandomNumberGenerator.GetRandomValue(1, 4)]
            };

            using (var stream = AddressClient.AddAddressEnrollments())
            {
                foreach (string enrollmentType in Konstants.AddressConstants.EnrollmentTypes)
                {
                    userAddress.Enrollment = enrollmentType;
                    await stream.RequestStream.WriteAsync(userAddress);
                }

                await stream.RequestStream.CompleteAsync();

                await stream;
                WriteLine($"Sent All");
            }


            /*
             * WriteLine("\n\nCreating New Professor ...");
             * while (response == "Y")
             * {
             *  // Add New Professor
             *  AddProfessorRequest professorNew = GenerateNewProfessor();
             *
             *  var newlyAddedProfessor = await Client.AddProfessorAsync(professorNew);
             *  WriteLine($"\n\nNew Professor Added with Professor Id: {newlyAddedProfessor.ProfessorId}");
             *
             *  WriteLine("\n\nDo you want to create New Professor: {Y/N}");
             *  response = ReadKey().KeyChar.ToString().ToUpper();
             * }
             */


            response = "Y";
            while (response == "Y")
            {
                WriteLine("\n\nPlease enter a Professor Id: ");
                var professorId = ReadLine();

                // Retrieve Single Row
                var professorRequest = new GetProfessorRequest {
                    ProfessorId = professorId
                };

                var professor = await CollegeClient.GetProfessorByIdAsync(professorRequest);

                DisplayProfessorDetails(professor);

                WriteLine("\n\nDo you want to Lookup a Professor: {Y/N}");
                response = ReadKey().KeyChar.ToString().ToUpper();
            }

            // Address Service gRPC
            var userAddress1 = new AddAddressRequest
            {
                StudentId   = Guid.NewGuid().ToString(), /* To Be replaced with Students's Id*/
                Name        = NameGenerator.GenerateName(12),
                FullAddress = AddressGenerator.GenerateAddress(),
                Enrollment  = Konstants.AddressConstants.EnrollmentTypes[RandomNumberGenerator.GetRandomValue(1, 4)]
            };


            var newAddress = await AddressClient.AddAddressAsync(userAddress1);

            WriteLine($"Address Data with Id: {newAddress.Id}");

            /*
             * response = "Y";
             * while (response == "Y")
             * {
             *  // Retrieve Multiple Rows
             *  var professors = await Client.GetAllProfessorsAsync(new Empty());
             *
             *  foreach (var prof in professors.Professors)
             *  {
             *      DisplayProfessorDetails(prof);
             *  }
             *
             *  WriteLine("\n\nDo you want to retrieve all professors: {Y/N}");
             *  response = ReadKey().KeyChar.ToString().ToUpper();
             * }
             */

            WriteLine("\n\nThank You for using the application. \n\nPress any key ...");
            ReadKey();
        }
示例#20
0
        static async Task Main(string[] args)
        {
            _config = new ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json").Build();

            var _collegeClient = CollegeServiceClientHelper.GetCollegeServiceClient(_config["RPCService:ServiceUrl"]);

            var _addressClient = AddressServiceClientHelper.GetAddressBookServerClient(_config["RPCService:ServiceUrl"]);

            var jwtToken = new JwtAccessToken();

            if (jwtToken.Expiration < DateTime.Now)
            {
                jwtToken = GetTokenFromAuth0();
            }

            var headers = new Metadata
            {
                { "Authorization", $"Bearer {jwtToken.Access_Token}" }
            };

            DisplayHeader("Retrieve Single Row ...");
            WriteLine("\n\nPlease enter a Professor Id: ");
            var professorId = ReadLine();

            var professorRequest = new GetProfessorRequest {
                ProfessorId = professorId
            };
            var professor = await _collegeClient.GetProfessorByIdAsync(professorRequest, headers : headers);

            DisplayProfessorDetails(professor);
            DisplayFooter();

            //**************** ADDRESS BOOK CLIENT SIDE STREAMING ****************//
            var userAddress = new AddAddressRequest
            {
                StudentId   = Guid.NewGuid().ToString(), /* To Be replaced with Students's Id*/
                Name        = NameGenerator.GenerateName(12),
                FullAddress = AddressGenerator.GenerateAddress(),
                Enrollment  = AddressConstants.EnrollmentTypes[RandomNumberGenerator.GetRandomValue(1, 4)]
            };

            using (var stream = _addressClient.AddAddressEnrollments())
            {
                foreach (string enrollmentType in AddressConstants.EnrollmentTypes)
                {
                    userAddress.Enrollment = enrollmentType;
                    await stream.RequestStream.WriteAsync(userAddress).ConfigureAwait(false);
                }

                await stream.RequestStream.CompleteAsync().ConfigureAwait(false);

                await stream;
                WriteLine($"Sent All");
            }
            //**************** ADDRESS BOOK CLIENT SIDE STREAMING ****************//

            //**************** ADDRESS BOOK SERVER SIDE STREAMING ****************//
            var studentEnrollmentsRequest = new AddressEnrollmentRequest
            {
                StudentId = "62b76fc7-46d9-4d1c-a246-7f4083a87634"
            };

            using var studentEnrollments = _addressClient
                                           .RetrieveAddressEnrollments(studentEnrollmentsRequest);
            try
            {
                await foreach (var studentEnrollment in studentEnrollments.ResponseStream.ReadAllAsync())
                {
                    WriteLine($"{studentEnrollment.StudentId} | {studentEnrollment.Name} | {studentEnrollment.Enrollment} | {studentEnrollment.EnrollmentStatus}");
                }
            }
            catch (RpcException ex) when(ex.StatusCode == StatusCode.Cancelled)
            {
                Console.WriteLine("Stream cancelled.");
            }
            //**************** ADDRESS BOOK SERVER SIDE STREAMING ****************//

            /*
             * DisplayHeader("Creating New Professor ...");
             * NewProfessorRequest professorNew = GenerateNewProfessor();
             * var newlyAddedProfessor = await _collegeClient.AddProfessorAsync(professorNew);
             * WriteLine($"\n\nNew Professor Added with Professor Id: {newlyAddedProfessor.ProfessorId}");
             * DisplayFooter();
             */

            //DisplayHeader("Retrieve Single Row ...");
            //WriteLine("\n\nPlease enter a Professor Id: ");
            //var professorId = ReadLine();

            //var professorRequest = new GetProfessorRequest { ProfessorId = professorId };
            //var professor = await _collegeClient.GetProfessorByIdAsync(professorRequest);

            //DisplayProfessorDetails(professor);
            //DisplayFooter();

            DisplayHeader("Retrieve All Rows ...");
            var professors = await _collegeClient.GetAllProfessorsAsync(new Empty());

            foreach (var prof in professors.Professors)
            {
                DisplayProfessorDetails(prof);
            }

            WriteLine("\n\nThank You for using the application. \n\nPress any key ...");
            ReadKey();
        }
示例#21
0
        static async Task Main(string[] args)
        {
            _config = new ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json").Build();

            var _collegeClient = CollegeServiceClientHelper.GetCollegeServiceClient(_config["RPCService:ServiceUrl"]);

            var _addressClient = AddressServiceClientHelper.GetAddressBookServerClient(_config["RPCService:ServiceUrl"]);

            //**************** ADDRESS BOOK ****************//
            var userAddress = new AddAddressRequest
            {
                StudentId   = Guid.NewGuid().ToString(), /* To Be replaced with Students's Id*/
                Name        = NameGenerator.GenerateName(12),
                FullAddress = AddressGenerator.GenerateAddress(),
                Enrollment  = AddressConstants.EnrollmentTypes[RandomNumberGenerator.GetRandomValue(1, 4)]
            };

            using (var stream = _addressClient.AddAddressEnrollments())
            {
                foreach (string enrollmentType in AddressConstants.EnrollmentTypes)
                {
                    userAddress.Enrollment = enrollmentType;
                    await stream.RequestStream.WriteAsync(userAddress).ConfigureAwait(false);
                }

                await stream.RequestStream.CompleteAsync().ConfigureAwait(false);

                await stream;
                WriteLine($"Sent All");
            }
            //**************** ADDRESS BOOK ****************//

            /*
             * DisplayHeader("Creating New Professor ...");
             * NewProfessorRequest professorNew = GenerateNewProfessor();
             * var newlyAddedProfessor = await _collegeClient.AddProfessorAsync(professorNew);
             * WriteLine($"\n\nNew Professor Added with Professor Id: {newlyAddedProfessor.ProfessorId}");
             * DisplayFooter();
             */

            //DisplayHeader("Retrieve Single Row ...");
            //WriteLine("\n\nPlease enter a Professor Id: ");
            //var professorId = ReadLine();

            //var professorRequest = new GetProfessorRequest { ProfessorId = professorId };
            //var professor = await _collegeClient.GetProfessorByIdAsync(professorRequest);

            //DisplayProfessorDetails(professor);
            //DisplayFooter();

            DisplayHeader("Retrieve All Rows ...");
            var professors = await _collegeClient.GetAllProfessorsAsync(new Empty());

            foreach (var prof in professors.Professors)
            {
                DisplayProfessorDetails(prof);
            }

            WriteLine("\n\nThank You for using the application. \n\nPress any key ...");
            ReadKey();
        }
示例#22
0
        static async Task Main(string[] args)
        {
            string response = "Y";

            _config = new ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json").Build();

            // gRPC Clients
            CollegeServiceClient    CollegeClient = CollegeServiceClientHelper.GetCollegeServiceClient(_config["RPCService:ServiceUrl"]);
            AddressBookServerClient AddressClient = AddressServiceClientHelper.GetAddressBookServerClient(_config["RPCService:ServiceUrl"]);

            /*
             * var cts = new CancellationTokenSource(TimeSpan.FromSeconds(50));
             *
             * using var replies = AddressClient.GetWeatherStream(new Empty(), cancellationToken: cts.Token);
             *
             * try
             * {
             *  await foreach (var weatherData in replies.ResponseStream.ReadAllAsync(cancellationToken: cts.Token))
             *  {
             *      Console.WriteLine($"{weatherData.DateTimeStamp.ToDateTime():s} | {weatherData.Summary} | {weatherData.TemperatureC} C");
             *  }
             * }
             * catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
             * {
             *  Console.WriteLine("Stream cancelled.");
             * }
             */

            // Address Enrollments Client Request for Server Streaming.
            var studentEnrollmentsRequest = new AddressEnrollmentRequest {
                StudentId = "3698FAED-83A1-4700-89EE-CAFE7716833E"
            };

            using var studentEnrollments = AddressClient.RetrieveAddressEnrollments(studentEnrollmentsRequest);

            try
            {
                await foreach (var studentEnrollment in studentEnrollments.ResponseStream.ReadAllAsync())
                {
                    Console.WriteLine($"{studentEnrollment.StudentId} {studentEnrollment.Name} {studentEnrollment.Enrollment} {studentEnrollment.EnrollmentStatus}");
                }
            }
            catch (RpcException ex) when(ex.StatusCode == StatusCode.Cancelled)
            {
                Console.WriteLine("Stream cancelled.");
            }

            // Address Enrollments Client Side Stream
            var userAddress = new AddAddressRequest
            {
                StudentId   = Guid.NewGuid().ToString(), /* To Be replaced with Students's Id*/
                Name        = NameGenerator.GenerateName(12),
                FullAddress = AddressGenerator.GenerateAddress(),
                Enrollment  = Konstants.AddressConstants.EnrollmentTypes[RandomNumberGenerator.GetRandomValue(1, 4)]
            };

            using (var stream = AddressClient.AddAddressEnrollments())
            {
                foreach (string enrollmentType in Konstants.AddressConstants.EnrollmentTypes)
                {
                    userAddress.Enrollment = enrollmentType;
                    await stream.RequestStream.WriteAsync(userAddress);
                }

                await stream.RequestStream.CompleteAsync();

                await stream;
                WriteLine($"Sent All");
            }


            /*
             * WriteLine("\n\nCreating New Professor ...");
             * while (response == "Y")
             * {
             *  // Add New Professor
             *  AddProfessorRequest professorNew = GenerateNewProfessor();
             *
             *  var newlyAddedProfessor = await Client.AddProfessorAsync(professorNew);
             *  WriteLine($"\n\nNew Professor Added with Professor Id: {newlyAddedProfessor.ProfessorId}");
             *
             *  WriteLine("\n\nDo you want to create New Professor: {Y/N}");
             *  response = ReadKey().KeyChar.ToString().ToUpper();
             * }
             */


            response = "Y";
            while (response == "Y")
            {
                WriteLine("\n\nPlease enter a Professor Id: ");
                var professorId = ReadLine();

                // Retrieve Single Row
                var professorRequest = new GetProfessorRequest {
                    ProfessorId = professorId
                };

                var professor = await CollegeClient.GetProfessorByIdAsync(professorRequest);

                DisplayProfessorDetails(professor);

                WriteLine("\n\nDo you want to Lookup a Professor: {Y/N}");
                response = ReadKey().KeyChar.ToString().ToUpper();
            }

            // Address Service gRPC
            var userAddress1 = new AddAddressRequest
            {
                StudentId   = Guid.NewGuid().ToString(), /* To Be replaced with Students's Id*/
                Name        = NameGenerator.GenerateName(12),
                FullAddress = AddressGenerator.GenerateAddress(),
                Enrollment  = Konstants.AddressConstants.EnrollmentTypes[RandomNumberGenerator.GetRandomValue(1, 4)]
            };


            var newAddress = await AddressClient.AddAddressAsync(userAddress1);

            WriteLine($"Address Data with Id: {newAddress.Id}");

            /*
             * response = "Y";
             * while (response == "Y")
             * {
             *  // Retrieve Multiple Rows
             *  var professors = await Client.GetAllProfessorsAsync(new Empty());
             *
             *  foreach (var prof in professors.Professors)
             *  {
             *      DisplayProfessorDetails(prof);
             *  }
             *
             *  WriteLine("\n\nDo you want to retrieve all professors: {Y/N}");
             *  response = ReadKey().KeyChar.ToString().ToUpper();
             * }
             */

            WriteLine("\n\nThank You for using the application. \n\nPress any key ...");
            ReadKey();
        }
示例#23
0
        private static void SendMessage()
        {
            var rnd     = new Random();
            var gender  = new string[] { "F", "M" }[rnd.Next(0, 2)];
            var address = AddressGenerator.Generate();

            var address1 = string.Format($"{address.Street} {address.HouseNo}");

            if (!" ".Contains(address.ApartmentNo))
            {
                address1 = string.Format($"{address1}, {address.ApartmentNo}");
            }

            var personCPR = new CPR()
            {
                CprNo         = CprGenerator.Generate(gender),
                FirstName     = NameGenerator.GenerateFirstName(gender),
                Surname       = NameGenerator.GenerateSurname(),
                Address1      = address1,
                Address2      = address.Address2,
                PostalCode    = address.PostalCode,
                City          = address.City,
                MaritalStatus = "Ugift",
                Spouse        = "",
                Children      = new List <string>(),
                Mother        = EuccidGenerator.Generate(new DateTime(1987, 11, 23)),
                Father        = EuccidGenerator.Generate(new DateTime(1984, 3, 18)),
                DoctorCVR     = "39227491",
                EuccidNo      = EuccidGenerator.Generate(),
                Gender        = gender,
            };

            Console.WriteLine("---------- CPR input: ----------");
            personCPR.PrintAll();

            // translate into CDM format
            var personCDM = CprTranslator.CprToCdm(personCPR);

            Console.WriteLine("\n---------- Translated into CDM: ----------");
            personCDM.PrintAll();

            // build message
            var message = new Message()
            {
                Body  = personCDM,
                Label = personCDM.ToString()
            };

            // build channel
            var path = @".\Private$\CPR_to_EUCCID";

            if (!MessageQueue.Exists(path))
            {
                MessageQueue.Create(path);
            }

            var cprToEuccidChannel = new MessageQueue(path)
            {
                Label = "CPR to EU-CCID"
            };

            // send
            cprToEuccidChannel.Send(message);

            Console.WriteLine("\n---------- Message sent. ----------\n\n");
        }
示例#24
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        private static void Main(string[] args)
        {
            var factory    = new RestIotaRepositoryFactory();
            var repo       = factory.CreateAsync(true).Result;
            var repository = new RestIotaRepository(new RestClient("http://localhost:14265"), new PoWService(new CpuPearlDiver()));
            var acc        = repository.GetAccountData(Seed.Random(), true, SecurityLevel.Medium, 0);

            var seed             = Seed.Random();
            var addressGenerator = new AddressGenerator(new Kerl(), new KeyGenerator(new Kerl(), new IssSigningHelper()));

            var addresses = addressGenerator.GetAddresses(seed, SecurityLevel.Medium, 0, 6);
            var addressesWithSpentInformation = repository.WereAddressesSpentFrom(addresses);

            var transactionStackCounter = 10;

            for (var i = 1; i <= transactionStackCounter; i++)
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                var transfers = new List <Transfer>();
                for (var j = 1; j <= i; j++)
                {
                    transfers.Add(new Transfer
                    {
                        Address =
                            new Address("YTXCUUWTXIXVRQIDSECVFRTKAFOEZITGDPLWYVUVFURMNVDPIRXEIQN9JHNFNVKVJMQVMA9GDZJROTSFZHIVJOVAEC")
                        {
                            Balance = 0
                        },
                        Message   = TryteString.FromAsciiString("Hello world! With " + i + " transactions."),
                        Tag       = new Tag("CSHARP"),
                        Timestamp = Timestamp.UnixSecondsTimestamp
                    });
                }

                var bundle = new Bundle();

                transfers.ForEach(bundle.AddTransfer);

                bundle.Finalize();
                bundle.Sign();

                var resultTransactions = repository.SendTrytes(bundle.Transactions, 27, 14);
                Console.WriteLine("Finished sending bundle with {0} transactions. Time elapsed: {1} seconds.", i, stopwatch.ElapsedMilliseconds / 1000);
            }


            var accountData = repository.GetAccountData(new Seed("SOMESEEDHERE"), true, SecurityLevel.Medium, 0);

            var latestInclusion =
                repository.GetLatestInclusion(
                    new List <Hash> {
                new Hash("HG9KCXQZGQDVTFGRHOZDZ99RMKGVRIQXEKXWXTPWYRGXQQVFVMTLQLUPJSIDONDEURVKHMBPRYGP99999")
            });

            var inputs = repository.GetInputs(new Seed("SOMESEEDHERE"), 99900000, SecurityLevel.Medium, 0);

            var newAddresses = repository.GetNewAddresses(Seed.Random(), 0, 5, SecurityLevel.Medium);

            var transactions =
                repository.FindTransactionsByAddresses(
                    new List <Address> {
                new Address("HHZSJANZQULQICZFXJHHAFJTWEITWKQYJKU9TYFA9AFJLVIYOUCFQRYTLKRGCVY9KPOCCHK99TTKQGXA9")
            });

            var tips             = repository.GetTips();
            var inclusionsStates =
                repository.GetInclusionStates(
                    new List <Hash> {
                new Hash("HG9KCXQZGQDVTFGRHOZDZ99RMKGVRIQXEKXWXTPWYRGXQQVFVMTLQLUPJSIDONDEURVKHMBPRYGP99999")
            },
                    tips.Hashes.GetRange(0, 10));

            var transactionTrytes =
                repository.GetTrytes(new List <Hash> {
                new Hash("HG9KCXQZGQDVTFGRHOZDZ99RMKGVRIQXEKXWXTPWYRGXQQVFVMTLQLUPJSIDONDEURVKHMBPRYGP99999")
            });

            var transactionData = transactionTrytes.Select(t => Transaction.FromTrytes(t)).ToList();

            var transactionsToApprove = repository.GetTransactionsToApprove();

            var balances =
                repository.GetBalances(
                    new List <Address>
            {
                new Address("GVZSJANZQULQICZFXJHHAFJTWEITWKQYJKU9TYFA9AFJLVIYOUCFQRYTLKRGCVY9KPOCCHK99TTKQGXA9"),
                new Address("HBBYKAKTILIPVUKFOTSLHGENPTXYBNKXZFQFR9VQFWNBMTQNRVOUKPVPRNBSZVVILMAFBKOTBLGLWLOHQ999999999")
            });

            var nodeInfo = repository.GetNodeInfo();

            var neighbours = repository.GetNeighbors();

            Console.WriteLine("Done");
            Console.ReadKey();
        }