Exemple #1
0
        public void AddAddress_book()
        {
            string FilePath = @"C:\Users\User\source\repos\ObjectOrientedProgramming\ObjectOrientedProgramming\Address Book\Address_book.json";
            string jsonAddressBookRecords = File.ReadAllText(FilePath);
            var    jsonAddressBookData    = JsonConvert.DeserializeObject <AddressBookListinfo>(jsonAddressBookRecords);
            List <GetAddressBookInfo> AddressBook;
            GetAddressBookInfo        AddressBookInfromation;

            try
            {
                if (jsonAddressBookRecords == "")
                {
                    AddressBook            = new List <GetAddressBookInfo>();
                    AddressBookInfromation = AddressBookUtility.AddAddressBook();
                    AddressBook.Add(AddressBookInfromation);
                }
                else
                {
                    AddressBook            = jsonAddressBookData.AddressBook;
                    AddressBookInfromation = AddressBookUtility.AddAddressBook();
                    AddressBook.Add(AddressBookInfromation);
                }
                AddressBookListinfo addresbook = new AddressBookListinfo()
                {
                    AddressBook = AddressBook
                };
                string jsondata = JsonConvert.SerializeObject(addresbook);
                File.WriteAllText(FilePath, jsondata);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #2
0
    static void Main()
    {
        //Skapa adressbok
        AddressBook addressBook = new AddressBook();

        //Lägg in några kontakter från början
        GenerateFakeContacts(addressBook);

        //Lägg in egna kontakter:
        Console.Write("First name: ");
        string firstName = Console.ReadLine();

        Console.Write("Last name: ");
        string         lastName   = Console.ReadLine();
        PrivateContact newContact = new PrivateContact();

        newContact.FirstName = firstName;
        newContact.LastName  = lastName;
        addressBook.Add(newContact);

        // Lista kontakter:
        foreach (Contact minKontakt in addressBook.GetContacts())
        {
            PrintContact(minKontakt);
        }
    }
Exemple #3
0
        private async Task AddToAddressBookForType(AddressRecordType type, ImportNotification draft)
        {
            AddressBook addressBook = await addressBookRepository.GetAddressBookForUser(userContext.UserId, type);

            switch (type)
            {
            case AddressRecordType.Facility:
                foreach (var facility in draft.Facilities.Facilities.Where(p => p.IsAddedToAddressBook))
                {
                    var facilityAddress = await FacilityAddressBookRecord(facility);

                    addressBook.Add(facilityAddress);
                }
                if (draft.Importer.IsAddedToAddressBook)
                {
                    var importerAddress = await ImporterAddressBookRecord(draft.Importer);

                    addressBook.Add(importerAddress);
                }
                break;

            case AddressRecordType.Producer:
                if (draft.Exporter.IsAddedToAddressBook)
                {
                    var exporter = await ExporterAddressBookRecord(draft.Exporter);

                    addressBook.Add(exporter);
                }

                if (draft.Producer.IsAddedToAddressBook)
                {
                    var producer = await ProducerAddressBookRecord(draft.Producer);

                    addressBook.Add(producer);
                }

                break;

            case AddressRecordType.Carrier:
            default:
                break;
            }
            await addressBookRepository.Update(addressBook);
        }
Exemple #4
0
    static void GenerateFakeContacts(AddressBook addressBook)
    {
        // 1. Lägg till kontakt via UI så småningom
        BusinessContact nyKontakt;

        nyKontakt           = new BusinessContact();
        nyKontakt.FirstName = "Lisa";
        nyKontakt.Company   = "BY";

        addressBook.Add(nyKontakt);

        PrivateContact nyPrivatKontakt = new PrivateContact();

        nyPrivatKontakt.FirstName    = "Arne";
        nyPrivatKontakt.RelationType = "It's complicated";
        nyPrivatKontakt.Birthday     = new DateTime(1981, 6, 1);

        addressBook.Add(nyPrivatKontakt);
    }
        /// <summary>
        /// Manage incoming messages
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cm_MessageEvent(object sender, MsgEventArgs e)
        {
            if (e.DataType == typeof(string))
            {
                bool    received = true;
                Message decoded  = Message.FromJson(e.Data as string);
                if (decoded.Sender == (sender as CommunicationModule).Id)
                {
                    received = false;
                }
                // we received a non decryptable message
                if (decoded.Kind == MessageKindType.VOID)
                {
                    return;
                }
                string displayName;
                this.Dispatcher.Invoke(() =>
                {
                    if (sender == userModule)
                    {
                        if (decoded.Kind == MessageKindType.USER)
                        {
                            if (Book.Add(decoded.Sender, (decoded as ChatUser)) &&
                                (decoded as ChatUser).Sender != UserProfile.Sender)
                            {
                                HelloMessage(decoded as ChatUser);
                            }
                        }
                    }
                    else
                    {
                        ChatUser cu     = Book.RetrieveUser(decoded.Sender);
                        displayName     = (cu != null) ? cu.Name + " " + cu.LastName : decoded.Sender.GetHashCode().ToString();
                        string verified = (decoded.Verified) ? "V+" : "!?";

                        if (received)
                        {
                            TextArea += string.Format("{0} {1}-{2}>> {3}{4}", verified, e.Timestamp.ToShortTimeString(), displayName, decoded.StringContent, Environment.NewLine);
                        }
                        else
                        {
                            TextArea += string.Format("{0} {1}-{2}-- {3}{4}", verified, e.Timestamp.ToShortTimeString(), displayName, decoded.StringContent, Environment.NewLine);
                        }
                        if (cu == null)
                        {
                            cu = new ChatUser()
                            {
                                Name = decoded.Sender.GetHashCode().ToString(), LastName = string.Empty
                            };
                        }
                        MessageList.Add(decoded, cu, received);
                    }
                });
            }
        }
        internal AddressBook Build()
        {
            var book = new AddressBook();

            // Add any non default addresses into the address book
            foreach (var builder in addressBuilders)
            {
                if (!defaultAddressBuilders.ContainsKey(builder.Key))
                {
                    book.Add(builder.Value.Build());
                }
            }

            return(book);
        }
Exemple #7
0
        private void AddCachedAddressBook_(string path)
        {
            //might be null if user sets filename
            if (path == null)
            {
                return;
            }

            var count = m_addressReadWrite.AddressFileLineCount(path);

            for (int i = 0; i < count; i++)
            {
                AddressBook.Add(m_addressFactory.Create());
            }

            foreach (var address in AddressBook)
            {
                m_addressReadWrite.ReadFile(path, address);
            }
        }
Exemple #8
0
 private void AddAddressInfo_()
 {
     AddressBook.Add(m_addressFactory.Create());
 }
Exemple #9
0
        static void Main(string[] args)
        {
            #region Configs creation.

            BlockchainStorageManagerParameters managerParameters = new BlockchainStorageManagerParameters()
            {
                BlocksInUnit = 2
            };
            UnitRepositoryParameters firstRepositoryParameters = new UnitRepositoryParameters()
            {
                DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain0")
            };
            UnitRepositoryParameters secondRepositoryParameters = new UnitRepositoryParameters()
            {
                DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain1")
            };
            WalletManagerParameters walletManagerParameters = new WalletManagerParameters()
            {
                WalletDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "wallets")
            };

            NetworkParameters networkParametersFirst = new NetworkParameters()
            {
                AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), FirstBookPath),

                PeerHostName = Dns.GetHostName(),
                PeerPort     = 8900,

                ClientTimeout = new TimeSpan(0, 0, 4),
                ServerTimeout = new TimeSpan(0, 0, 4)
            };

            NetworkParameters networkParametersSecond = new NetworkParameters()
            {
                AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), SecondBookPath),

                PeerHostName = Dns.GetHostName(),
                PeerPort     = 8910,

                ClientTimeout = new TimeSpan(0, 0, 4),
                ServerTimeout = new TimeSpan(0, 0, 4)
            };

            BasicMiningFactoryParameters parameters = new BasicMiningFactoryParameters()
            {
                HashLeastUpFactor = 1.25,
                HashMostUpFactor  = 1.75,

                HashLeastDownFactor = 0.25,
                HashMostDownFactor  = 0.75,

                DifficultyLeastUpFactor = 1.25,
                DifficultyMostUpFactor  = 1.75,

                DifficultyLeastDownFactor = 0.25,
                DifficultyMostDownFactor  = 0.75,

                MinDifficulty = Difficulty
            };

            JsonSerializer jsonSerializer = new JsonSerializer()
            {
                Formatting = Formatting.Indented
            };

            using (Stream jsonFile = File.Open(MiningConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, parameters);

            using (Stream jsonFile = File.Open(ManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, managerParameters);

            using (Stream jsonFile = File.Open(FirstRepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, firstRepositoryParameters);

            using (Stream jsonFile = File.Open(SecondRepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, secondRepositoryParameters);

            using (Stream jsonFile = File.Open(WalletManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, walletManagerParameters);

            using (Stream jsonFile = File.Open(FirstNetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, networkParametersFirst);

            using (Stream jsonFile = File.Open(SecondNetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, networkParametersSecond);

            JsonBasicMiningFactoryConfig       miningConfig           = new JsonBasicMiningFactoryConfig(MiningConfigPath);
            JsonBlockchainStorageManagerConfig managerConfig          = new JsonBlockchainStorageManagerConfig(ManagerConfigPath);
            JsonUnitRepositoryConfig           firstRepositoryConfig  = new JsonUnitRepositoryConfig(FirstRepositoryConfigPath);
            JsonUnitRepositoryConfig           secondRepositoryConfig = new JsonUnitRepositoryConfig(SecondRepositoryConfigPath);
            JsonWalletManagerConfig            walletManagerConfig    = new JsonWalletManagerConfig(WalletManagerConfigPath);
            JsonNetworkConfig firstNetworkConfig  = new JsonNetworkConfig(FirstNetworkConfigPath);
            JsonNetworkConfig secondNetworkConfig = new JsonNetworkConfig(SecondNetworkConfigPath);

            #endregion

            #region Directory remove.

            removeDirectory(firstRepositoryConfig.DirectoryPath);
            removeDirectory(secondRepositoryConfig.DirectoryPath);
            removeDirectory(walletManagerConfig.WalletDirectoryPath);

            #endregion

            #region Directory creation.

            Directory.CreateDirectory(firstRepositoryParameters.DirectoryPath);
            Directory.CreateDirectory(secondRepositoryParameters.DirectoryPath);
            Directory.CreateDirectory(Path.Combine(firstRepositoryConfig.DirectoryPath, "addressers"));
            Directory.CreateDirectory(Path.Combine(firstRepositoryConfig.DirectoryPath, "units"));
            Directory.CreateDirectory(Path.Combine(secondRepositoryConfig.DirectoryPath, "addressers"));
            Directory.CreateDirectory(Path.Combine(secondRepositoryConfig.DirectoryPath, "units"));
            Directory.CreateDirectory(walletManagerConfig.WalletDirectoryPath);

            #endregion

            #region Initial units.

            // Addressers.
            string firstAddresser0Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "addressers", "addresser0.addr");
            string secondAddresser0Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "addressers", "addresser0.addr");

#if (CREATE_EXTRA_FILE)
            string firstAddresser1Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "addressers", "addresser1.addr");
            string secondAddresser1Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "addressers", "addresser1.addr");
#endif

            File.Create(firstAddresser0Path).Close();
            File.Create(secondAddresser0Path).Close();

#if (CREATE_EXTRA_FILE)
            File.Create(firstAddresser1Path).Close();
            File.Create(secondAddresser1Path).Close();
#endif

            // Units.
            string firstUnit0Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "units", "unit0.unit");
            string secondUnit0Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "units", "unit0.unit");

#if (CREATE_EXTRA_FILE)
            string firstUnit1Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "units", "unit1.unit");
            string secondUnit1Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "units", "unit1.unit");
#endif

            File.Create(firstUnit0Path).Close();
            File.Create(secondUnit0Path).Close();

#if (CREATE_EXTRA_FILE)
            File.Create(firstUnit1Path).Close();
            File.Create(secondUnit1Path).Close();
#endif

            BlockchainUnit firstUnit0  = new BlockchainUnit(firstUnit0Path, new AddressStorage(firstAddresser0Path));
            BlockchainUnit secondUnit0 = new BlockchainUnit(secondUnit0Path, new AddressStorage(secondAddresser0Path));

            #endregion

            IMiningFactory    miningFactory          = new BasicMiningFactory(miningConfig);
            IHashFactory      hashFactory            = miningFactory.GetMiningHashFactoryById(3);
            IHashFactory      transactionHashFactory = new TransactionHashFactory();
            ISignatureFactory signatureFactory       = new ECDSAFactory();
            IWalletManager    walletManager          = new WalletManager(walletManagerConfig, signatureFactory, transactionHashFactory);

            Wallet firstWallet = walletManager.AddNewWallet();

            #region Initial transactions.

            LinkedList <Transaction> firstInitialList  = new LinkedList <Transaction>();
            LinkedList <Transaction> secondInitialList = new LinkedList <Transaction>();

            Transaction firstInitialTransaction  = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 32, transactionHashFactory);
            Transaction secondInitialTransaction = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 19, transactionHashFactory);
            Transaction thirdInitialTransaction  = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 32, transactionHashFactory);
            Transaction fourthInitialTransaction = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 19, transactionHashFactory);

            firstInitialTransaction.SignTransaction(firstWallet.Signer);
            secondInitialTransaction.SignTransaction(firstWallet.Signer);
            thirdInitialTransaction.SignTransaction(firstWallet.Signer);
            fourthInitialTransaction.SignTransaction(firstWallet.Signer);

            firstInitialList.AddLast(firstInitialTransaction);
            firstInitialList.AddLast(secondInitialTransaction);
            secondInitialList.AddLast(thirdInitialTransaction);
            secondInitialList.AddLast(fourthInitialTransaction);

            #endregion

            #region Initial blocks.

            IHashFactory miningHashFactory = miningFactory.GetMiningHashFactoryById(3);
            IMiner       miner             = new BasicMiner(3, Difficulty, miningHashFactory);

            Block firstInitialBlock = new Block(firstWallet.PublicKey, new byte[hashFactory.GetDigest().HashLength], firstInitialList, hashFactory);

            miner.MineBlock(firstInitialBlock);
            firstInitialBlock.SignBlock(firstWallet.Signer);

            Block secondInitialBlock = new Block(firstWallet.PublicKey, firstInitialBlock.Hash, secondInitialList, hashFactory);

            miner.MineBlock(secondInitialBlock);
            secondInitialBlock.SignBlock(firstWallet.Signer);

            firstUnit0.AddBlock(firstInitialBlock);
            firstUnit0.AddBlock(secondInitialBlock);
            secondUnit0.AddBlock(firstInitialBlock);
            secondUnit0.AddBlock(secondInitialBlock);

            firstUnit0.Dispose();
            secondUnit0.Dispose();

            #endregion

            UnitRepository firstRepository  = new UnitRepository(firstRepositoryConfig);
            UnitRepository secondRepository = new UnitRepository(secondRepositoryConfig);

            BlockchainStorageManager firstManager  = new BlockchainStorageManager(managerConfig, firstRepository);
            BlockchainStorageManager secondManager = new BlockchainStorageManager(managerConfig, secondRepository);

            Blockchain firstBlockchain  = new Blockchain(firstWallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, firstManager);
            Wallet     secondWallet     = walletManager.AddNewWallet();
            Blockchain secondBlockchain = new Blockchain(secondWallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, secondManager);

            #region Address books creation.

            File.Create(FirstBookPath).Close();
            File.Create(SecondBookPath).Close();

            PeerAddress firstPeer  = new PeerAddress(firstWallet.PublicKey);
            PeerAddress secondPeer = new PeerAddress(secondWallet.PublicKey);

            AddressBook firstPeerAddressBook  = new AddressBook(FirstBookPath);
            AddressBook secondPeerAddressBook = new AddressBook(SecondBookPath);

            firstPeerAddressBook.Add(secondPeer, "ws://" + secondNetworkConfig.PeerHostName + $":{secondNetworkConfig.PeerPort}/simplecoin");
            secondPeerAddressBook.Add(firstPeer, "ws://" + firstNetworkConfig.PeerHostName + $":{firstNetworkConfig.PeerPort}/simplecoin");

            firstPeerAddressBook.SaveOnDrive();
            secondPeerAddressBook.SaveOnDrive();

            #endregion

            #region Network.

            IBroadcaster firstNetwork = new Network(firstBlockchain, firstPeerAddressBook, firstNetworkConfig, firstWallet.Signer);

            IBroadcaster secondNetwork = new Network(secondBlockchain, secondPeerAddressBook, secondNetworkConfig, secondWallet.Signer);

            firstBlockchain.NetworkBroadcaster  = firstNetwork;
            secondBlockchain.NetworkBroadcaster = secondNetwork;

            firstNetwork.Start();
            secondNetwork.Start();

            #endregion

            firstWallet.Blockchain  = firstBlockchain;
            secondWallet.Blockchain = secondBlockchain;

            firstWallet.SendTokens(16, secondWallet.PublicKey);
            firstWallet.SendTokens(8, secondWallet.PublicKey);

            secondBlockchain.ProcessPendingTransactions();

            secondWallet.SendTokens(8, firstWallet.PublicKey);
            firstBlockchain.ProcessPendingTransactions();

            Console.WriteLine("First blockchain:\n");

            foreach (Block block in firstBlockchain)
            {
                Console.WriteLine(JsonConvert.SerializeObject(block, Formatting.Indented));
                Console.WriteLine();
            }

            Console.WriteLine("--------------------------------------------------------------------------------------");

            Console.WriteLine("Second blockchain:\n");

            foreach (Block block in secondBlockchain)
            {
                Console.WriteLine(JsonConvert.SerializeObject(block, Formatting.Indented));
                Console.WriteLine();
            }

            Console.WriteLine("}\n");

            Console.WriteLine(firstBlockchain.IsValid ? "First blockchain is valid" : "First blockchain is invalid");
            Console.WriteLine(firstBlockchain.IsValid ? "Second blockchain is valid" : "Second blockchain is invalid");

            Console.WriteLine($"Cryptocurrency ownership for first wallet: {firstBlockchain.CountBalanceForWallet(firstWallet.PublicKey)}");
            Console.WriteLine($"Cryptocurrency ownership for second wallet: {firstBlockchain.CountBalanceForWallet(secondWallet.PublicKey)}");
        }
        public void Insert(Address address)
        {
            addressBook.Add(address);

            addressBook.Save();
        }