/// <summary> /// Create an administrator. /// </summary> private void CreateAdministrator() { ISession session = SnCore.Data.Hibernate.Session.Current; Account a = (Account)session.CreateCriteria(typeof(Account)) .SetMaxResults(1) .UniqueResult(); if (a != null) { return; } a = new Account(); a.Name = "Administrator"; a.Password = ManagedAccount.GetPasswordHash("password"); a.IsAdministrator = true; a.IsPasswordExpired = true; a.Created = a.Modified = a.LastLogin = DateTime.UtcNow; a.Birthday = DateTime.UtcNow; a.TimeZone = -1; session.Save(a); AccountEmail ae = new AccountEmail(); ae.Account = a; ae.Address = "*****@*****.**"; ae.Created = ae.Modified = a.Created; ae.Principal = true; ae.Verified = true; session.Save(ae); session.Flush(); ManagedAccount ma = new ManagedAccount(session, a); ma.CreateAccountSystemMessageFolders(ManagedAccount.GetAdminSecurityContext(session)); }
[Test] // foodcandy bug #421 : Discuss: edit button not visible for author public void TestCanEdit() { ManagedAccount account = new ManagedAccount(Session); ManagedDiscussionPost m_post = new ManagedDiscussionPost(Session); try { string email = GetNewEmailAddress(); TransitAccount t_instance = new TransitAccount(); t_instance.Password = GetNewString(); t_instance.Name = GetNewString(); t_instance.Birthday = DateTime.UtcNow; int account_id = account.Create(email, t_instance, GetSecurityContext()); TransitDiscussionPost t_post = GetTransitInstance(); t_post.AccountId = GetSecurityContext().Account.Id; m_post.CreateOrUpdate(t_post, GetSecurityContext()); Session.Flush(); ManagedDiscussionPost m_post1 = new ManagedDiscussionPost(Session, m_post.Id); TransitDiscussionPost t_post1 = m_post1.GetTransitInstance(GetSecurityContext()); Assert.IsTrue(t_post1.CanDelete, "Owner should be able to delete his own message."); Assert.IsTrue(t_post1.CanEdit, "Owner should be able to edit his own message."); TransitDiscussionPost t_post2 = m_post1.GetTransitInstance(account.GetSecurityContext()); Assert.IsFalse(t_post2.CanDelete, "User shouldn't be able to delete someone else's message."); Assert.IsFalse(t_post2.CanEdit, "User shouldn't be able to edit someone else's message."); } finally { account.Delete(GetSecurityContext()); m_post.Delete(GetSecurityContext()); } }
public void CreateAccountWebsiteAccrossAccounts() { ManagedAccount a = new ManagedAccount(Session); ManagedAccount b = new ManagedAccount(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); b.Create("Test User 2", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); TransitAccountWebsite ta = new TransitAccountWebsite(); ta.Name = "My Website"; ta.Description = "Lots of details."; ta.Url = "http://www.dblock.org"; ManagedAccountWebsite m_a = new ManagedAccountWebsite(Session); m_a.CreateOrUpdate(ta, a.GetSecurityContext()); ManagedAccountWebsite m_b = new ManagedAccountWebsite(Session); m_b.CreateOrUpdate(ta, b.GetSecurityContext()); } finally { a.Delete(a.GetSecurityContext()); b.Delete(b.GetSecurityContext()); } }
public void GetAccountFriendAuditEntriesCountTest() { string ticket = ManagedAccount.GetAdminTicket(Session); int id = ManagedAccount.GetAdminAccount(Session).Id; int count = WebServiceImpl <TransitAccountAuditEntry, ManagedAccountAuditEntry, AccountAuditEntry> .GetSQLCount( ticket, string.Format( "INNER JOIN AccountFriend AccountFriend ON ( " + "AccountAuditEntry.Account_Id = AccountFriend.Account_Id OR AccountAuditEntry.Account_Id = AccountFriend.Keen_Id " + ") WHERE ( " + " ( AccountFriend.Account_Id = {0} OR AccountFriend.Keen_Id = {0} )" + " AND AccountAuditEntry.Account_Id <> {0}" + ")", id)); Console.WriteLine("Count: {0}", count); List <TransitAccountAuditEntry> rs = WebServiceImpl <TransitAccountAuditEntry, ManagedAccountAuditEntry, AccountAuditEntry> .GetList( ticket, null, "SELECT {AccountAuditEntry.*} FROM AccountAuditEntry {AccountAuditEntry} " + string.Format( "INNER JOIN AccountFriend AccountFriend ON ( " + "AccountAuditEntry.Account_Id = AccountFriend.Account_Id OR AccountAuditEntry.Account_Id = AccountFriend.Keen_Id " + ") WHERE ( " + " ( AccountFriend.Account_Id = {0} OR AccountFriend.Keen_Id = {0} )" + " AND AccountAuditEntry.Account_Id <> {0}" + ")", id), "AccountAuditEntry"); Console.WriteLine("Result Set: {0}", rs.Count); }
public void RejectAccountFriend() { ManagedAccount a = new ManagedAccount(Session); ManagedAccount b = new ManagedAccount(Session); try { a.Create("Test User 1", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); a.VerifyAllEmails(); b.Create("Test User 2", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); b.VerifyAllEmails(); ManagedAccountFriendRequest r = new ManagedAccountFriendRequest(Session, a.CreateAccountFriendRequest( AdminSecurityContext, b.Id, "Please be my friend!")); r.Reject(AdminSecurityContext, "no thanks!"); } finally { a.Delete(a.GetSecurityContext()); b.Delete(b.GetSecurityContext()); } }
private async Task VerificaExistenciaSmartContract() { if (contractAddress == string.Empty) { account = new ManagedAccount(senderAddress, password); geth = new Web3Geth(account, "http://localhost:8501"); try { var transactionHash = await geth.Eth.DeployContract.SendRequestAsync(abi, bytecode, senderAddress, new Nethereum.Hex.HexTypes.HexBigInteger(900000), 5); var receipt = await geth.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash); while (receipt == null) { Thread.Sleep(5000); receipt = await geth.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash); } contractAddress = receipt.ContractAddress; } catch (Exception chingadamadre) { Console.WriteLine("Message: " + chingadamadre.Message); Console.WriteLine("InnerException: " + chingadamadre.InnerException); Console.WriteLine("Source: " + chingadamadre.Source); } } }
public void CreateDiscussionThread() { ManagedAccount a = new ManagedAccount(Session); ManagedDiscussion d = new ManagedDiscussion(Session); ManagedDiscussionPost p = new ManagedDiscussionPost(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); a.VerifyAllEmails(); a.AddDefaultPicture(); TransitDiscussion t_d = new TransitDiscussion(); t_d.Description = GetNewString(); t_d.Name = GetNewString(); t_d.Personal = false; d.CreateOrUpdate(t_d, a.GetSecurityContext()); TransitDiscussionPost t_p = new TransitDiscussionPost(); t_p.Subject = GetNewString(); t_p.Body = GetNewString(); t_p.DiscussionId = d.Id; p.CreateOrUpdate(t_p, a.GetSecurityContext()); Session.Flush(); } finally { p.Delete(a.GetSecurityContext()); d.Delete(a.GetSecurityContext()); a.Delete(a.GetSecurityContext()); } }
public async Task <bool> IsCheckCustomer(string CustomerId) { _account = _account ?? _web3Backend.GetDefaultAccount(); _web3 = _web3 ?? _web3Backend.GetDefaultWeb3(); var address = await _walletService.GetWalletAdress(CustomerId); var addr = address?.RemoveHexPrefix().Trim('0'); if (string.IsNullOrEmpty(addr)) { return(false); } _checkcontract = _checkcontract ?? await _contracts.GetContract("PostdatedCheckManager", _config.GetSection("NetworkId").Value); CheckModels.IsCustomerInputFunction inputFunc = new CheckModels.IsCustomerInputFunction() { Address = address, FromAddress = _account.Address }; var handler = _web3.Eth.GetContractQueryHandler <CheckModels.IsCustomerInputFunction>(); var result = await handler.QueryDeserializingToObjectAsync <CheckModels.IsCustomerOutputModel>(inputFunc, _checkcontract.Address); return(await Task.FromResult(result.IsCustomer)); }
/// <summary> /// 提示无效的账户--(Geth / Parity) /// </summary> /// <returns></returns> public async Task ShouldBeAbleToTransferBetweenAccountsUsingManagedAccount() { var senderAddress = "0x09f8F8c219D94A5db8Ee466dC072748603A7A0D9"; var addressTo = "0xCbbA01495C541FDcCE6F05b52f420D7c9eA018B4"; var password = "******"; // A managed account is an account which is maintained by the client (Geth / Parity) var account = new ManagedAccount(senderAddress, password); var web3 = new Web3(account); Debug.Log(account.Address); Debug.Log(addressTo); //The transaction receipt polling service is a simple utility service to poll for receipts until mined var transactionPolling = web3.TransactionManager.TransactionReceiptService; var currentBalance = await web3.Eth.GetBalance.SendRequestAsync(addressTo); //assumed client is mining already //When sending the transaction using the transaction manager for a managed account, personal_sendTransaction is used. var transactionReceipt = await transactionPolling.SendRequestAndWaitForReceiptAsync(() => web3.TransactionManager.SendTransactionAsync(account.Address, addressTo, new HexBigInteger(1000000000000000000))//1ETH ); var newBalance = await web3.Eth.GetBalance.SendRequestAsync(addressTo); Debug.Log((currentBalance.Value + 1000000000000000000) + " " + newBalance.Value); }
public async Task <int> CreateCheck(string fromAddress, string ToAddress, DateTime CheckDate, uint Amount) { _account = _account ?? _web3Backend.GetAccount(fromAddress); _web3 = _web3 ?? _web3Backend.GetWeb3(_account); _checkcontract = _checkcontract ?? await _contracts.GetContract("PostdatedCheckManager", _config.GetSection("NetworkId").Value); CheckModels.CreateCheckInputFunction inputFunc = new CheckModels.CreateCheckInputFunction() { FromAddress = fromAddress, To = ToAddress, Amount = Amount, CheckDate = CheckDate.ToUnixTimestampTicks() }; var handler = _web3.Eth.GetContractTransactionHandler <CheckModels.CreateCheckInputFunction>(); var result = await handler.SendRequestAndWaitForReceiptAsync(_checkcontract.Address, inputFunc); var logResult = await CreatedLastCheck(fromAddress); return(logResult.CheckId); }
public void CreateAccountStoryPicture() { ManagedAccount a = new ManagedAccount(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); a.VerifyAllEmails(); a.AddDefaultPicture(); TransitAccountStory s = new TransitAccountStory(); s.Name = GetNewString(); s.Summary = GetNewString(); ManagedAccountStory ms = new ManagedAccountStory(Session); int story_id = ms.CreateOrUpdate(s, a.GetSecurityContext()); TransitAccountStoryPicture p = new TransitAccountStoryPicture(); p.Name = GetNewString(); p.AccountStoryId = story_id; ManagedAccountStoryPicture mp = new ManagedAccountStoryPicture(Session); mp.CreateOrUpdate(p, a.GetSecurityContext()); } finally { a.Delete(AdminSecurityContext); Session.Flush(); } }
public void Reject(ManagedSecurityContext sec, string message) { GetACL().Check(sec, DataOperation.Update); Account requester = mInstance.Account; Account approver = mInstance.Keen; if (!string.IsNullOrEmpty(message)) { ManagedAccount recepient = new ManagedAccount(Session, requester); ManagedSiteConnector.TrySendAccountEmailMessageUriAsAdmin(Session, recepient, string.Format("EmailAccountFriendRequestReject.aspx?id={0}&message={1}", this.Id, Renderer.UrlEncode(message))); // delete the request when user notified Collection <AccountFriendRequest> .GetSafeCollection(mInstance.Account.AccountFriendRequests).Remove(mInstance); Session.Delete(mInstance); } else { // silently reject the request mInstance.Rejected = true; Session.Save(mInstance); } }
public void VerifyEmailInvalid() { ManagedAccount a = new ManagedAccount(Session); a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); Session.Flush(); try { IList list = Session.CreateCriteria(typeof(AccountEmail)) .Add(Expression.Eq("Account.Id", a.Id)) .List(); foreach (AccountEmail e in list) { IList confirmationslist = Session.CreateCriteria(typeof(AccountEmailConfirmation)) .Add(Expression.Eq("AccountEmail.Id", e.Id)) .List(); foreach (AccountEmailConfirmation c in confirmationslist) { Assert.AreEqual(false, c.AccountEmail.Verified); new ManagedAccountEmailConfirmation(Session, c.Id).Verify("invalid code"); Assert.AreEqual(false, c.AccountEmail.Verified); } } Session.Flush(); } finally { a.Delete(AdminSecurityContext); Session.Flush(); } }
public void CreatePlaceQueue() { ManagedAccount a = new ManagedAccount(Session); PlaceQueue q = null; try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); TransitPlaceQueue t_q = new TransitPlaceQueue(); t_q.AccountId = a.Id; t_q.Name = GetNewString(); t_q.PublishAll = false; t_q.PublishFriends = true; q = t_q.GetInstance(Session, a.GetSecurityContext()); q.Created = q.Modified = DateTime.UtcNow; Session.Save(q); Session.Flush(); Assert.IsTrue(q.Id > 0, "Place queue not commited"); } finally { if (q != null) { Session.Delete(q); } a.Delete(AdminSecurityContext); } }
private async void QuorumContractInteraction() { QuorumSettings qs = new QuorumSettings(); WalletSettings ws = new WalletSettings(); var account = await GetAccount(); var managedAccount = new ManagedAccount(account.Address, ws.Password); var web3Managed = new Web3(managedAccount, qs.UrlWithAccessKey); try { var blockNumber = await web3Managed.Eth.Blocks.GetBlockNumber.SendRequestAsync(); var print = "Current BlockNumber: " + blockNumber.Value; var balance = await web3Managed.Eth.GetBalance.SendRequestAsync(account.Address); print += "\n" + "Account Balance of " + account.Address + " on Quorum: " + Web3.Convert.FromWei(balance.Value); var contract = web3Managed.Eth.GetContract(qs.ContractAbi, qs.ContractAddress); var functionSet = contract.GetFunction("getLatestFileIndex"); var result = await functionSet.CallAsync <int>(); print += $"\ngetLatestFileIndex(): " + result; consoleMessage.text = print; } catch (Exception e) { consoleMessage.text = "Error: Check Debug Log\nPossibly no internet access!"; Debug.Log(e); } }
private static async Task TestService(string fromAddress, string password) { var account = new ManagedAccount(fromAddress, password); var web3 = new Web3Geth(account); var gas = new HexBigInteger(900000); Console.WriteLine("DeployContract"); string contractAddress = await UUIDProviderContractService.DeployContractAsync(web3, fromAddress, null, gas); IUUIDProviderContractService service = new UUIDProviderContractService(web3, contractAddress); byte[] uuid1 = await service.GenerateUUID4CallAsync(fromAddress, gas); var guid1 = new Guid(uuid1); Console.WriteLine($"guid1 = {guid1}"); string trans = await service.GenerateUUID4Async(fromAddress, gas); var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(trans); while (receipt == null) { Thread.Sleep(1000); receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(trans); } byte[] uuid2 = await service.GenerateUUID4CallAsync(fromAddress, gas); var guid2 = new Guid(uuid2); Console.WriteLine($"guid2 = {guid2}"); }
public void CreateManyStoriesPerAccount(int count, int wordsperstory) { Random r = new Random(); IList accounts = Session.CreateCriteria(typeof(Account)).List(); foreach (Account a in accounts) { for (int i = 0; i < count; i++) { TransitAccountStory s = new TransitAccountStory(); s.Name = Guid.NewGuid().ToString(); List <string> words = new List <string>(wordsperstory); for (int w = 0; w < wordsperstory; w++) { StringBuilder word = new StringBuilder(); int len = r.Next() % 10 + 1; for (int l = 0; l < len; l++) { word.Append((char)(r.Next() % 26 + 'a')); } s.Summary = s.Summary + word.ToString() + (w == 0 ? "" : " "); } ManagedAccount ma = new ManagedAccount(Session, a); ManagedAccountStory ms = new ManagedAccountStory(Session); ms.CreateOrUpdate(s, ma.GetSecurityContext()); } } }
public void CreateAccountSurvey() { ManagedAccount a = new ManagedAccount(Session); ManagedSurvey m_survey = new ManagedSurvey(Session); ManagedSurveyQuestion m_question = new ManagedSurveyQuestion(Session); ManagedAccountSurveyAnswer m_answer = new ManagedAccountSurveyAnswer(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); TransitSurvey t_survey = new TransitSurvey(); t_survey.Name = GetNewString(); m_survey.CreateOrUpdate(t_survey, AdminSecurityContext); TransitSurveyQuestion t_question = new TransitSurveyQuestion(); t_question.SurveyId = m_survey.Id; t_question.Question = GetNewString(); m_question.CreateOrUpdate(t_question, AdminSecurityContext); TransitAccountSurveyAnswer ta = new TransitAccountSurveyAnswer(); ta.SurveyQuestionId = m_question.Id; ta.Answer = GetNewString(); m_answer.CreateOrUpdate(ta, a.GetSecurityContext()); } finally { m_answer.Delete(a.GetSecurityContext()); a.Delete(AdminSecurityContext); m_survey.Delete(AdminSecurityContext); Session.Flush(); } }
public async Task ShouldBeAbleToDeployAContract() { var senderAddress = "0x12890d2cce102216644c59daE5baed380d84830c"; var password = "******"; var abi = @"[{""constant"":false,""inputs"":[{""name"":""a"",""type"":""int256""}],""name"":""multiply"",""outputs"":[{""name"":""r"",""type"":""int256""}],""type"":""function""},{""inputs"":[{""name"":""multiplier"",""type"":""int256""}],""type"":""constructor""}]"; var byteCode = "0x606060405260405160208060ae833981016040528080519060200190919050505b806000600050819055505b5060768060386000396000f360606040526000357c0100000000000000000000000000000000000000000000000000000000900480631df4f144146037576035565b005b604b60048080359060200190919050506061565b6040518082815260200191505060405180910390f35b6000600060005054820290506071565b91905056"; var multiplier = 7; //a managed account uses personal_sendTransanction with the given password, this way we don't need to unlock the account for a certain period of time var account = new ManagedAccount(senderAddress, password); //using the specific geth web3 library to allow us manage the mining. var web3 = new Geth.Web3Geth(account); var transactionHash = await web3.Eth.DeployContract.SendRequestAsync(abi, byteCode, senderAddress, multiplier); var miningResult = await web3.Miner.Start.SendRequestAsync(6); var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash); while (receipt == null) { Thread.Sleep(1000); receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash); } var contractAddress = receipt.ContractAddress; var contract = web3.Eth.GetContract(abi, contractAddress); var multiplyFunction = contract.GetFunction("multiply"); var result = await multiplyFunction.CallAsync <int>(7); Assert.Equal(49, result); }
public static async Task <bool> Login(string username, string password) { try { await using (db = new DropCoinDbContext()) { User = await db.Users.FirstOrDefaultAsync(p => p.UserName == username); Account = new ManagedAccount(User.DrpAddress, password); Web3 = new Web3Geth(Account, RpcUrl); if (await Web3.Personal.UnlockAccount.SendRequestAsync(Account.Address, Account.Password, 120)) { return(true); } return(false); } } catch (Exception e) { MessageBox.Show(e.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } }
public override TransitBug GetTransitInstance(ManagedSecurityContext sec) { TransitBug t_instance = base.GetTransitInstance(sec); t_instance.AccountName = ManagedAccount.GetAccountNameWithDefault(Session, t_instance.AccountId); return(t_instance); }
public async System.Threading.Tasks.Task <ActionResult> CreateAsync(EthereumContractViewModel ethereumContractViewModelViewModel) { string fileHash; if (ModelState.IsValid) { using (var md5 = MD5.Create()) { var hash = md5.ComputeHash(ethereumContractViewModelViewModel.FileUpload.InputStream); fileHash = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } var senderAddress = "0xCBE60Eaea0cB3fb07348c72F68D8ec9a604aa941"; var password = "******"; var abi = @"[{'constant':true,'inputs':[],'name':'getActive','outputs':[{'name':'','type':'bool'}],'payable':false,'stateMutability':'view','type':'function'},{'constant':false,'inputs':[{'name':'_active','type':'bool'}],'name':'setActive','outputs':[],'payable':false,'stateMutability':'nonpayable','type':'function'},{'constant':true,'inputs':[],'name':'getDocument','outputs':[{'name':'','type':'string'}],'payable':false,'stateMutability':'view','type':'function'},{'inputs':[{'name':'_requester','type':'address'},{'name':'_recipient','type':'address'},{'name':'_document','type':'string'}],'payable':false,'stateMutability':'nonpayable','type':'constructor'}]"; var byteCode = "608060405234801561001057600080fd5b506040516103443803806103448339810160409081528151602080840151928401516001805461010060a860020a031916610100600160a060020a03808716919091029190911790915560028054600160a060020a03191691861691909117905590930180519193909161008a9160009190840190610093565b5050505061012e565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100d457805160ff1916838001178555610101565b82800160010185558215610101579182015b828111156101015782518255916020019190600101906100e6565b5061010d929150610111565b5090565b61012b91905b8082111561010d5760008155600101610117565b90565b6102078061013d6000396000f3006080604052600436106100555763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416629ebb10811461005a578063acec338a14610083578063b6f3f14d1461009f575b600080fd5b34801561006657600080fd5b5061006f610129565b604080519115158252519081900360200190f35b34801561008f57600080fd5b5061009d6004351515610132565b005b3480156100ab57600080fd5b506100b4610145565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100ee5781810151838201526020016100d6565b50505050905090810190601f16801561011b5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60015460ff1690565b6001805460ff1916911515919091179055565b60008054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156101d15780601f106101a6576101008083540402835291602001916101d1565b820191906000526020600020905b8154815290600101906020018083116101b457829003601f168201915b50505050509050905600a165627a7a723058200425d4931a5ca733f20ef9228d18cb0c8d3e62f794101a25813ca3fcb04d8d070029"; var account = new ManagedAccount(senderAddress, password); var web3 = new Web3(account); web3.TransactionManager.DefaultGas = BigInteger.Parse("290000"); web3.TransactionManager.DefaultGasPrice = Transaction.DEFAULT_GAS_PRICE; var webGeth = new Web3Geth(account); webGeth.TransactionManager.DefaultGas = BigInteger.Parse("290000"); webGeth.TransactionManager.DefaultGasPrice = Transaction.DEFAULT_GAS_PRICE; var unlockAccount = await web3.Personal.UnlockAccount.SendRequestAsync(senderAddress, password, 120); await webGeth.Miner.Start.SendRequestAsync(6); var transactionHash = await web3.Eth.DeployContract.SendRequestAsync(abi, byteCode, senderAddress, new Nethereum.Hex.HexTypes.HexBigInteger(120), new Nethereum.Hex.HexTypes.HexBigInteger(120), "0xCBE60Eaea0cB3fb07348c72F68D8ec9a604aa941", "0xCBE60Eaea0cB3fb07348c72F68D8ec9a604aa941", fileHash); var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash); while (receipt == null) { Thread.Sleep(5000); receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash); } var mineResult = await webGeth.Miner.Stop.SendRequestAsync(); var contractAddress = receipt.ContractAddress; var contract = web3.Eth.GetContract(abi, contractAddress); EthereumContractViewModel EthereumContractViewModel = new EthereumContractViewModel() { ContractID = ethereumContractViewModelViewModel.ContractID }; _EthereumContractRepository.Add(EthereumContractViewModel); return(RedirectToAction("Index")); } return(View(ethereumContractViewModelViewModel)); }
protected override void Check(TransitAccountMessage t_instance, ManagedSecurityContext sec) { base.Check(t_instance, sec); // existing instance doesn't need to be rechecked if (t_instance.Id != 0) { return; } // verified e-mail required sec.CheckVerified(); // is the sender a friend of the receiver? int sender_id = t_instance.GetOwner(Session, t_instance.SenderAccountId, sec).Id; ManagedAccount sender = new ManagedAccount(Session, sender_id); if (sender.HasFriend(t_instance.RecepientAccountId)) { return; } // how many messages within the last hour? new ManagedQuota(DefaultHourlyLimit).Check <AccountMessage, ManagedAccount.QuotaExceededException>( GetAcountMessages(Session, sender_id, DateTime.UtcNow.AddHours(-1))); // how many messages within the last 24 hours? ManagedQuota.GetDefaultEnabledQuota().Check <AccountMessage, ManagedAccount.QuotaExceededException>( GetAcountMessages(Session, sender_id, DateTime.UtcNow.AddDays(-1))); // check whether the sender was flagged new ManagedQuota(ManagedAccountFlag.DefaultAccountFlagThreshold).Check <AccountFlag, ManagedAccountFlag.AccountFlaggedException>( ManagedAccountFlag.GetAccountFlagsByFlaggedAccountId(Session, sender_id)); }
protected override void Save(ManagedSecurityContext sec) { bool fNew = (mInstance.Id == 0); if (mInstance.Id == 0) { mInstance.Sent = DateTime.UtcNow; } base.Save(sec); Session.Flush(); if (fNew) { ManagedAccount recepient = new ManagedAccount(Session, mInstance.RecepientAccountId); ManagedSiteConnector.TrySendAccountEmailMessageUriAsAdmin( Session, recepient, string.Format("EmailAccountMessage.aspx?id={0}", mInstance.Id)); // save a copy in Sent items AccountMessage copy = new AccountMessage(); copy.Account = Session.Load <Account>(mInstance.SenderAccountId); copy.AccountMessageFolder = ManagedAccountMessageFolder.FindRootFolder(Session, mInstance.SenderAccountId, "sent"); copy.Body = mInstance.Body; copy.RecepientAccountId = mInstance.RecepientAccountId; copy.SenderAccountId = mInstance.SenderAccountId; copy.Sent = mInstance.Sent; copy.Subject = mInstance.Subject; copy.Unread = true; Session.Save(copy); } }
public override int CreateOrUpdate(TransitAccountGroupAccountRequest t_instance, ManagedSecurityContext sec) { ManagedAccountGroup m_group = new ManagedAccountGroup(Session, t_instance.AccountGroupId); if (m_group.HasAccountRequest(t_instance.AccountId)) { throw new Exception(string.Format( "You already have a membership request pending to join \"{0}\".", m_group.Instance.Name)); } if (m_group.HasAccount(t_instance.AccountId)) { throw new Exception(string.Format( "You are already a member of \"{0}\".", m_group.Instance.Name)); } int id = base.CreateOrUpdate(t_instance, sec); Session.Flush(); foreach (AccountGroupAccount accountadmin in Collection <AccountGroupAccount> .GetSafeCollection(mInstance.AccountGroup.AccountGroupAccounts)) { if (accountadmin.IsAdministrator) { ManagedAccount recepient = new ManagedAccount(Session, accountadmin.Account.Id); ManagedSiteConnector.TrySendAccountEmailMessageUriAsAdmin( Session, recepient, string.Format("EmailAccountGroupAccountRequest.aspx?id={0}", id)); } } return(id); }
public void Accept(ManagedSecurityContext sec, string message) { GetACL().Check(sec, DataOperation.Delete); AccountPlace place = new AccountPlace(); place.Account = mInstance.Account; place.Place = mInstance.Place; place.Created = place.Modified = DateTime.UtcNow; place.Type = mInstance.Type; place.Description = string.Format("System-approved on {0}.", DateTime.UtcNow.ToString()); Session.Save(place); if (mInstance.Account.AccountPlaces == null) { mInstance.Account.AccountPlaces = new List <AccountPlace>(); } mInstance.Account.AccountPlaces.Add(place); if (mInstance.Place.AccountPlaces == null) { mInstance.Place.AccountPlaces = new List <AccountPlace>(); } mInstance.Place.AccountPlaces.Add(place); ManagedAccount recepient = new ManagedAccount(Session, mInstance.Account); ManagedSiteConnector.TrySendAccountEmailMessageUriAsAdmin(Session, recepient, string.Format("EmailAccountPlaceRequestAccept.aspx?id={0}&message={1}", this.Id, Renderer.UrlEncode(message))); // delete the request when user notified Collection <AccountPlaceRequest> .GetSafeCollection(mInstance.Account.AccountPlaceRequests).Remove(mInstance); Session.Delete(mInstance); }
public void Accept(ManagedSecurityContext sec, string message) { GetACL().Check(sec, DataOperation.AllExceptUpdate); ManagedAccountGroup group = new ManagedAccountGroup(Session, mInstance.AccountGroup); if (!group.HasAccount(mInstance.Requester.Id)) { Session.Delete(mInstance); throw new Exception(string.Format("Sorry, {0} is no longer member of \"{2}\".", mInstance.Requester.Name)); } // account may already a member (invited twice by different admins, etc.) if (!group.HasAccount(mInstance.Account.Id)) { JoinGroup(sec, message); ManagedAccount recepient = new ManagedAccount(Session, mInstance.Requester); ManagedSiteConnector.TrySendAccountEmailMessageUriAsAdmin( Session, recepient, string.Format("EmailAccountGroupAccountInvitationAccept.aspx?id={0}&aid={1}&message={2}", this.Id, sec.Account.Id, Renderer.UrlEncode(message))); } Session.Delete(mInstance); }
public async Task ShouldBeAbleToTransferBetweenAccountsUsingManagedAccount() { var senderAddress = "0x12890d2cce102216644c59daE5baed380d84830c"; var addressTo = "0x13f022d72158410433cbd66f5dd8bf6d2d129924"; var password = "******"; // A managed account is an account which is maintained by the client (Geth / Parity) var account = new ManagedAccount(senderAddress, password); var web3 = new Web3.Web3(account); //The transaction receipt polling service is a simple utility service to poll for receipts until mined var transactionPolling = (TransactionReceiptPollingService)web3.TransactionManager.TransactionReceiptService; var currentBalance = await web3.Eth.GetBalance.SendRequestAsync(addressTo); //assumed client is mining already //When sending the transaction using the transaction manager for a managed account, personal_sendTransaction is used. var txnHash = await web3.TransactionManager.SendTransactionAsync(account.Address, addressTo, new HexBigInteger(20)); var receipt = await transactionPolling.PollForReceiptAsync(txnHash); var newBalance = await web3.Eth.GetBalance.SendRequestAsync(addressTo); Assert.Equal(currentBalance.Value + 20, newBalance.Value); }
public void CreateDiscussion() { ManagedAccount a = new ManagedAccount(Session); ManagedDiscussion d = new ManagedDiscussion(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); a.VerifyAllEmails(); a.AddDefaultPicture(); TransitDiscussion t = new TransitDiscussion(); t.Name = GetNewString(); t.Description = GetNewString(); t.AccountId = a.Id; t.Personal = false; t.Created = t.Modified = DateTime.UtcNow; d.CreateOrUpdate(t, a.GetSecurityContext()); Session.Flush(); } finally { d.Delete(a.GetSecurityContext()); a.Delete(a.GetSecurityContext()); } }
public override int CreateOrUpdate(TransitAccountGroupAccountInvitation t_instance, ManagedSecurityContext sec) { ManagedAccountGroup m_group = new ManagedAccountGroup(Session, t_instance.AccountGroupId); ManagedAccount m_account = new ManagedAccount(Session, t_instance.AccountId); if (m_group.HasAccountInvitation(t_instance.AccountId) || m_group.HasAccountRequest(t_instance.AccountId)) { throw new Exception(string.Format("An invitation for {0} to join \"{1}\" is already pending.", m_account.Instance.Name, m_group.Instance.Name)); } if (m_group.HasAccount(t_instance.AccountId)) { throw new Exception(string.Format("{0} is already a member of \"{1}\".", m_account.Name, m_group.Instance.Name)); } int id = base.CreateOrUpdate(t_instance, sec); Session.Flush(); ManagedAccount recepient = new ManagedAccount(Session, t_instance.AccountId); ManagedSiteConnector.TrySendAccountEmailMessageUriAsAdmin( Session, recepient, string.Format("EmailAccountGroupAccountInvitation.aspx?id={0}", id)); return(id); }
// Function to retreive data form the blockchain private async Task <string> RetrieveFromBlockchain() { QuorumSettings qs = new QuorumSettings(); WalletSettings ws = new WalletSettings(); try { var account = await BlockchainContractInteraction.GetAccount(); var managedAccount = new ManagedAccount(account.Address, ws.Password); var web3Managed = new Web3(managedAccount, qs.UrlWithAccessKey); var web3 = new Web3(account, qs.UrlWithAccessKey); var contract = web3.Eth.GetContract(qs.ContractAbi, qs.ContractAddress); var functionSet = contract.GetFunction("getHash"); var result = await functionSet.CallAsync <string>(2); return(result); } catch (System.Exception e) { consoleMessage.text = "Error: Check Debug Log\nPossibly no internet access!"; Debug.Log(e); return(null); } }
public void TestCleanupStaleAccounts_1() { ManagedSecurityContext sec = ManagedAccount.GetAdminSecurityContext(Session); string email = string.Format("{0}@sncore.com", Guid.NewGuid().ToString()); // create an account with an unverified e-mail, make sure the e-mail is sent ManagedAccount ma = new ManagedAccount(Session); int id = ma.Create("TestCleanupStaleAccounts", "password", email, DateTime.UtcNow, sec); bool fDeleted = false; try { Session.Flush(); // get the account as is, update the login date/time to four months behind Account a = Session.Load<Account>(id); a.LastLogin = DateTime.UtcNow.AddMonths(-4); Session.Save(a); Session.Flush(); // update the e-mail as if it was added 3 months ago AccountEmail e = (AccountEmail) a.AccountEmails[0]; Assert.AreEqual(e.Created, e.Modified); e.Created = e.Modified = a.LastLogin; Session.Save(e); // check that the account has a single confirmation e-mail pending Console.WriteLine("Email dates: {0}/{1}", e.Created, e.Modified); service.RunCleanupStaleAccounts(Session, ManagedAccount.GetAdminSecurityContext(Session)); Session.Refresh(e); Console.WriteLine("Email dates: {0}/{1}", e.Created, e.Modified); Assert.AreNotEqual(e.Created, e.Modified); // move e-mail modified date in the past -> account should be deleted e.Modified = e.Modified.AddMonths(-3); Session.Save(e); Session.Flush(); service.RunCleanupStaleAccounts(Session, ManagedAccount.GetAdminSecurityContext(Session)); a = (Account)Session.CreateCriteria(typeof(Account)) .Add(Expression.Eq("Id", id)) .UniqueResult(); Assert.IsNull(a); fDeleted = true; } finally { if (!fDeleted) { ma.Delete(sec); } } }
public void CreateAccountEmailMessage() { ManagedAccount a = new ManagedAccount(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); a.SendAccountEmailMessage("*****@*****.**", "*****@*****.**", "subject", "body", true); } finally { a.Delete(AdminSecurityContext); } }
public void VerifyEmail() { ManagedAccount a = new ManagedAccount(Session); a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); Session.Flush(); try { a.VerifyAllEmails(); } finally { a.Delete(AdminSecurityContext); Session.Flush(); } }
public void TestCleanupStaleAccounts_2() { ManagedSecurityContext sec = ManagedAccount.GetAdminSecurityContext(Session); string email = string.Format("{0}@sncore.com", Guid.NewGuid().ToString()); // create an account with an unverified e-mail, make sure the e-mail is sent ManagedAccount ma = new ManagedAccount(Session); int id = ma.Create("TestCleanupStaleAccounts", "password", email, DateTime.UtcNow, sec); ManagedAccount mb = new ManagedAccount(Session); int id2 = mb.Create("TestCleanupStaleAccounts", "password", email, DateTime.UtcNow, sec); mb.VerifyAllEmails(); bool fDeleted = false; try { Session.Flush(); // get the account as is, update the login date/time to four months behind Account a = Session.Load<Account>(id); a.LastLogin = DateTime.UtcNow.AddMonths(-4); Session.Save(a); Session.Flush(); // this should delete the stale account, since there's another one verified service.RunCleanupStaleAccounts(Session, ManagedAccount.GetAdminSecurityContext(Session)); a = (Account)Session.CreateCriteria(typeof(Account)) .Add(Expression.Eq("Id", id)) .UniqueResult(); Assert.IsNull(a); fDeleted = true; } finally { if (!fDeleted) { ma.Delete(sec); } mb.Delete(sec); } }
public void VerifyEmailWithReclaim() { ManagedAccount a = new ManagedAccount(Session); ManagedAccount b = new ManagedAccount(Session); try { a.Create("TestVerifyEmailReclaim1", "password", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); a.VerifyAllEmails(); b.Create("TestVerifyEmailReclaim2", "password", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); b.VerifyAllEmails(); { IList list = Session.CreateCriteria(typeof(AccountEmail)) .Add(Expression.Eq("Account.Id", a.Id)) .List(); foreach (AccountEmail e in list) { Assert.AreEqual(false, e.Verified); } } { IList list = Session.CreateCriteria(typeof(AccountEmail)) .Add(Expression.Eq("Account.Id", b.Id)) .List(); foreach (AccountEmail e in list) { Assert.AreEqual(true, e.Verified); } } } finally { a.Delete(a.GetSecurityContext()); b.Delete(b.GetSecurityContext()); } Session.Flush(); }
public void AddAccountEmail() { ManagedAccount a = new ManagedAccount(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); TransitAccountEmail t_instance = new TransitAccountEmail(); t_instance.Address = "*****@*****.**"; t_instance.AccountId = a.Id; ManagedAccountEmail m_instance = new ManagedAccountEmail(Session); m_instance.CreateOrUpdate(t_instance, a.GetSecurityContext()); } finally { a.Delete(AdminSecurityContext); } }
public void CreateManyAccounts(int count) { ManagedSecurityContext sec = ManagedAccount.GetAdminSecurityContext(Session); TransitCountry tc = new TransitCountry(); tc.Name = Guid.NewGuid().ToString(); TransitState ts = new TransitState(); ts.Name = Guid.NewGuid().ToString(); ts.Country = tc.Name; ManagedCountry c = new ManagedCountry(Session); c.CreateOrUpdate(tc, sec); ManagedState s = new ManagedState(Session); s.CreateOrUpdate(ts, sec); TransitAccountAddress ta = new TransitAccountAddress(); ta.Apt = "123"; ta.City = "New York"; ta.Country = tc.Name; ta.Name = "My Address"; ta.State = ts.Name; ta.Street = "Houston St."; ta.Zip = "10001"; for (int i = 0; i < count; i++) { ManagedAccount a = new ManagedAccount(Session); string name = Guid.NewGuid().ToString(); a.Create( name, "password", string.Format("{0}@localhost.com", name), DateTime.UtcNow, sec); ManagedAccountAddress ma = new ManagedAccountAddress(Session); ma.CreateOrUpdate(ta, a.GetSecurityContext()); } }
public void CreateAccountWebsiteInvalid() { ManagedAccount a = new ManagedAccount(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); TransitAccountWebsite ta = new TransitAccountWebsite(); ta.Name = "My Website"; ta.Description = "Lots of details."; ta.Url = "<script>attack!</script>"; ManagedAccountWebsite m_w = new ManagedAccountWebsite(Session); m_w.CreateOrUpdate(ta, a.GetSecurityContext()); } finally { a.Delete(AdminSecurityContext); } }
public void CreateAccountAddress() { ManagedAccount a = new ManagedAccount(Session); ManagedCountry c = new ManagedCountry(Session); ManagedState s = new ManagedState(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); TransitCountry tc = new TransitCountry(); tc.Name = GetNewString(); TransitState ts = new TransitState(); ts.Name = GetNewString(); ts.Country = tc.Name; c.CreateOrUpdate(tc, AdminSecurityContext); s.CreateOrUpdate(ts, AdminSecurityContext); TransitAccountAddress ta = new TransitAccountAddress(); ta.Apt = "123"; ta.City = "New York"; ta.Country = tc.Name; ta.Name = "My Address"; ta.State = ts.Name; ta.Street = "Houston St."; ta.Zip = "10001"; ManagedAccountAddress m_a = new ManagedAccountAddress(Session); m_a.CreateOrUpdate(ta, new ManagedSecurityContext(a.Instance)); } finally { a.Delete(AdminSecurityContext); s.Delete(AdminSecurityContext); c.Delete(AdminSecurityContext); Session.Flush(); } }
public static bool TrySendAccountEmailMessageUriAsAdmin( ISession session, ManagedAccount recepient, string relativeuri) { try { string sendto = string.Empty; if (!recepient.TryGetActiveEmailAddress(out sendto, ManagedAccount.GetAdminSecurityContext(session))) return false; MailAddress address = new MailAddress(sendto, recepient.Name); return TrySendAccountEmailMessageUriAsAdmin( session, address.ToString(), relativeuri); } catch { return false; } }
public void RunTagWords(ISession session, ManagedSecurityContext sec) { DateTime newRun = DateTime.UtcNow; ICriteria c = session.CreateCriteria(typeof(Account)); if (mLastRun.HasValue) { // last run is updated on interval, add some safe time c.Add(Expression.Gt("LastLogin", mLastRun.Value.AddMinutes(-30))); } IList accounts = c.List(); foreach (Account account in accounts) { if (IsStopping) break; try { ManagedAccount ma = new ManagedAccount(session, account); ma.UpdateTagWords(); } catch (ThreadAbortException) { throw; } catch { } Thread.Sleep(1000 * InterruptInterval); } session.Flush(); mLastRun = newRun; }
public void CreatePlaceWebsite() { ManagedAccount a = new ManagedAccount(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); TransitPlaceWebsite ta = new TransitPlaceWebsite(); ta.Name = "My Website"; ta.Description = "Lots of details."; ta.Url = "http://www.dblock.org"; ta.PlaceId = _place.Instance.Id; ManagedPlaceWebsite m_a = new ManagedPlaceWebsite(Session); m_a.CreateOrUpdate(ta, a.GetSecurityContext()); m_a.Delete(a.GetSecurityContext()); } finally { a.Delete(a.GetSecurityContext()); } }
public void DeleteAccountEmailInvalid() { ManagedAccount a = new ManagedAccount(Session); try { a.Create("Test User", "testpassword", "*****@*****.**", DateTime.UtcNow, AdminSecurityContext); IList list = Session.CreateCriteria(typeof(AccountEmail)) .Add(Expression.Eq("Account.Id", a.Id)) .List(); foreach (AccountEmail e in list) { ManagedAccountEmail email = new ManagedAccountEmail(Session, e); email.Delete(AdminSecurityContext); } } finally { a.Delete(AdminSecurityContext); } }
public int ImportCampaignAccountEmails(string ticket, int campaign_id, bool verified_emails, bool unverified_emails) { using (SnCore.Data.Hibernate.Session.OpenConnection()) { ISession session = SnCore.Data.Hibernate.Session.Current; ManagedSecurityContext sec = new ManagedSecurityContext(session, ticket); ITransaction trans = session.BeginTransaction(); int count = 0; try { ICriteria c = session.CreateCriteria(typeof(Account)); IList list = c.List(); foreach (Account account in list) { ManagedAccount ma = new ManagedAccount(session, account); if (ma.HasVerifiedEmail(sec)) { if (!verified_emails) continue; } else { if (!unverified_emails) continue; } CampaignAccountRecepient existing = (CampaignAccountRecepient)session.CreateCriteria(typeof(CampaignAccountRecepient)) .Add(Expression.Eq("Account.Id", ma.Id)) .Add(Expression.Eq("Campaign.Id", campaign_id)) .UniqueResult(); if (existing != null) continue; ManagedCampaignAccountRecepient newrecepient = new ManagedCampaignAccountRecepient(session); TransitCampaignAccountRecepient newtransitrecepient = new TransitCampaignAccountRecepient(); newtransitrecepient.AccountId = ma.Id; newtransitrecepient.CampaignId = campaign_id; newtransitrecepient.Created = newtransitrecepient.Modified = DateTime.UtcNow; newtransitrecepient.Sent = false; newrecepient.CreateOrUpdate(newtransitrecepient, sec); count++; } trans.Commit(); SnCore.Data.Hibernate.Session.Flush(); } catch { trans.Rollback(); throw; } return count; } }
public string CreateAccountWithInvitationAndLogin(int invitationid, string code, TransitAccount ta) { int id = CreateAccountWithInvitation(invitationid, code, ta); using (SnCore.Data.Hibernate.Session.OpenConnection()) { ISession session = SnCore.Data.Hibernate.Session.Current; ManagedAccount acct = new ManagedAccount(session, id); string ticket = ManagedAccount.GetTicketFromAccountId(acct.Id); return ticket; } }
public int CreateAccountWithInvitation(int invitationid, string code, TransitAccount ta) { using (SnCore.Data.Hibernate.Session.OpenConnection()) { ISession session = SnCore.Data.Hibernate.Session.Current; ManagedAccountInvitation invitation = new ManagedAccountInvitation(session, invitationid); if (invitation.Code != code) { throw new ManagedAccount.AccessDeniedException(); } ManagedAccount acct = new ManagedAccount(session); int id = acct.Create(invitation.Instance.Email, ta, true, ManagedAccount.GetAdminSecurityContext(session)); // become friends with the person who invited you TransitAccountFriend t_friend = new TransitAccountFriend(); AccountFriend friend = new AccountFriend(); friend.Account = session.Load<Account>(invitation.AccountId); friend.Keen = session.Load<Account>(id); friend.Created = DateTime.UtcNow; session.Save(friend); SnCore.Data.Hibernate.Session.Flush(); // notify that a friend has joined ManagedAccount recepient = new ManagedAccount(session, invitation.AccountId); ManagedSiteConnector.TrySendAccountEmailMessageUriAsAdmin(session, recepient, string.Format("EmailAccountInvitationAccept.aspx?id={0}&aid={1}", invitation.Id, id)); // if this is a group invitation, join the group if (invitation.Instance.AccountGroup != null) { AccountGroupAccountInvitation groupInvitation = new AccountGroupAccountInvitation(); groupInvitation.Account = session.Load<Account>(id); groupInvitation.AccountGroup = invitation.Instance.AccountGroup; groupInvitation.Created = invitation.Instance.Created; groupInvitation.Modified = invitation.Instance.Modified; groupInvitation.Requester = session.Load<Account>(invitation.AccountId); ManagedAccountGroupAccountInvitation mGroupInvitation = new ManagedAccountGroupAccountInvitation( session, groupInvitation); mGroupInvitation.JoinGroup(ManagedAccount.GetAdminSecurityContext(session), string.Empty); } invitation.Delete(ManagedAccount.GetAdminSecurityContext(session)); SnCore.Data.Hibernate.Session.Flush(); return acct.Id; } }
public void DeclineInvitation(int id, string code) { using (SnCore.Data.Hibernate.Session.OpenConnection()) { ISession session = SnCore.Data.Hibernate.Session.Current; ManagedAccountInvitation invitation = new ManagedAccountInvitation(session, id); if (invitation.Code != code) { throw new ManagedAccount.AccessDeniedException(); } ManagedAccount recepient = new ManagedAccount(session, invitation.AccountId); ManagedSiteConnector.TrySendAccountEmailMessageUriAsAdmin(session, recepient, string.Format("EmailAccountInvitationReject.aspx?id={0}", invitation.Id)); invitation.Delete(ManagedAccount.GetAdminSecurityContext(session)); SnCore.Data.Hibernate.Session.Flush(); } }
public void DemoteAdministrator(string ticket, int id) { int userid = GetAccountId(ticket); using (SnCore.Data.Hibernate.Session.OpenConnection()) { ISession session = SnCore.Data.Hibernate.Session.Current; // check permissions: userid must have admin rights to the Accounts table ManagedAccount user = new ManagedAccount(session, userid); if (!user.IsAdministrator()) { throw new ManagedAccount.AccessDeniedException(); } if (user.Id == id) { throw new Exception("You cannot demote self."); } ManagedAccount acct = new ManagedAccount(session, id); if (!acct.IsAdministrator()) { throw new Exception("User is not an administrator."); } acct.DemoteAdministrator(); SnCore.Data.Hibernate.Session.Flush(); } }
public string Impersonate(string ticket, int id) { int userid = GetAccountId(ticket); using (SnCore.Data.Hibernate.Session.OpenConnection()) { ISession session = SnCore.Data.Hibernate.Session.Current; // check permissions: userid must have admin rights to the Accounts table ManagedAccount user = new ManagedAccount(session, userid); if (!user.IsAdministrator()) { throw new ManagedAccount.AccessDeniedException(); } ManagedAccount acct = new ManagedAccount(session, id); string return_ticket = ManagedAccount.GetTicketFromAccountId(acct.Id); SnCore.Data.Hibernate.Session.Flush(); return return_ticket; } }
public void ChangePasswordMd5(string ticket, int accountid, string oldpasswordhash, string newpassword) { int userid = GetAccountId(ticket); using (SnCore.Data.Hibernate.Session.OpenConnection()) { ISession session = SnCore.Data.Hibernate.Session.Current; if (userid != accountid) { ManagedAccount requester = new ManagedAccount(session, userid); if (!requester.IsAdministrator()) { throw new ManagedAccount.AccessDeniedException(); } ManagedAccount account = new ManagedAccount(session, accountid); account.ResetPassword(newpassword, true); } else { ManagedAccount account = new ManagedAccount(session, accountid); account.ChangePasswordMd5(oldpasswordhash, newpassword); } SnCore.Data.Hibernate.Session.Flush(); } }
public void RunSystemReminders(ISession session, ManagedSecurityContext sec) { // get reminders IList reminders = session.CreateCriteria(typeof(Reminder)) .Add(Expression.Eq("Enabled", true)) .List(); foreach (Reminder reminder in reminders) { if (IsStopping) break; reminder.LastRun = DateTime.UtcNow; reminder.LastRunError = string.Empty; session.Save(reminder); ManagedReminder mr = new ManagedReminder(session, reminder); try { // get the type of the object seeked Type objecttype = Assembly.GetAssembly(typeof(DataObject)) .GetType(reminder.DataObject.Name, true); // todo: currently this works with date-based fields only // anything older than this time DateTime timeboundary = DateTime.UtcNow.AddHours(-reminder.DeltaHours); // find all records matching the property IList objects = session.CreateCriteria(objecttype) .Add(Expression.Le(reminder.DataObjectField, timeboundary)) .List(); // currently only support account identities // the object is either an Account object or has an AccountId property string accountidproperty = (reminder.DataObject.Name == "Account") ? "Id" : "AccountId"; PropertyInfo accountidpropertyinfo = objecttype.GetProperty(accountidproperty); if (accountidpropertyinfo == null) { throw new Exception(string.Format("Object {0} does not have a property {1}.", reminder.DataObject.Name, accountidproperty)); } foreach (object o in objects) { if (IsStopping) break; int accountid = (int)accountidpropertyinfo.GetValue(o, null); ReminderEvent reminderevent = (ReminderEvent)session.CreateCriteria(typeof(ReminderEvent)) .Add(Expression.Eq("Reminder.Id", reminder.Id)) .Add(Expression.Eq("Account.Id", accountid)) .UniqueResult(); Account acct = session.Load<Account>(accountid); ManagedAccount ma = new ManagedAccount(session, acct); try { if (reminderevent == null) { reminderevent = new ReminderEvent(); reminderevent.Account = acct; reminderevent.Reminder = reminder; reminderevent.Created = reminderevent.Modified = DateTime.UtcNow; } else { if (reminderevent.Modified >= timeboundary) { // this field was already noticed and event was fired in a prior run continue; } if (!reminder.Recurrent) { // this reminder has already been sent but is not recurrent continue; } reminderevent.Modified = DateTime.UtcNow; } if (!mr.CanSend(acct)) continue; ManagedSiteConnector.TrySendAccountEmailMessageUriAsAdmin( session, ma, string.Format("{0}?id={1}", reminder.Url, ma.Id)); session.Save(reminderevent); } catch (ThreadAbortException) { throw; } catch (Exception ex) { EventLogManager.WriteEntry(string.Format("Error sending a reminder at {0} to account id {1}: {2}", reminder.Url, accountid, ex.Message), EventLogEntryType.Warning); } } } catch (ThreadAbortException) { throw; } catch (Exception ex) { reminder.LastRunError = ex.Message; session.Save(reminder); } Thread.Sleep(1000 * InterruptInterval); } }
public void RunSubscriptions(ISession session, ManagedSecurityContext sec) { IEnumerable<AccountRssWatch> rsswatchs = session.CreateQuery( "FROM AccountRssWatch AccountRssWatch" + " WHERE AccountRssWatch.Enabled = 1" + " AND DATEDIFF(hour, AccountRssWatch.Sent, getutcdate()) > AccountRssWatch.UpdateFrequency" + " ORDER BY AccountRssWatch.Sent ASC") .Enumerable<AccountRssWatch>(); IEnumerator<AccountRssWatch> enumerator = rsswatchs.GetEnumerator(); while (enumerator.MoveNext() && ! IsStopping) { AccountRssWatch rsswatch = enumerator.Current; rsswatch.LastError = string.Empty; DateTime utcnow = DateTime.UtcNow; try { ManagedAccountRssWatch m_rsswatch = new ManagedAccountRssWatch(session, rsswatch); if (m_rsswatch.HasSubscriptionUpdates(sec)) { ManagedAccount ma = new ManagedAccount(session, rsswatch.Account); ManagedSiteConnector.TrySendAccountEmailMessageUriAsAdmin( session, ma, string.Format("AccountRssWatchView.aspx?id={0}", m_rsswatch.Id)); } } catch (ThreadAbortException) { throw; } catch (Exception ex) { rsswatch.LastError = ex.Message; } finally { rsswatch.Sent = utcnow; session.Save(rsswatch); session.Flush(); } Thread.Sleep(1000 * InterruptInterval); } }
public void RunCleanupStaleAccounts(ISession session, ManagedSecurityContext sec) { // fetch accounts that have not been logged in for two months and that don't have a verified e-mail IEnumerable<Account> accounts = session.CreateQuery( string.Format( "FROM Account account" + " WHERE NOT EXISTS ( " + " FROM AccountEmail AS email" + " WHERE email.Account = account" + " AND email.Verified = 1" + ") AND account.LastLogin < '{0}'", DateTime.UtcNow.AddMonths(-2).ToString(DateTimeFormatInfo.InvariantInfo))) .Enumerable<Account>(); IEnumerator<Account> enumerator = accounts.GetEnumerator(); while (enumerator.MoveNext() && ! IsStopping) { Account account = enumerator.Current; try { ManagedAccount ma = new ManagedAccount(session, account); bool bDelete = false; // delete an account without any e-mail addresses (openid) if (account.AccountEmails == null || account.AccountEmails.Count == 0) { bDelete = true; } if (account.AccountEmails != null && !bDelete) { // see if there exists another account with the same verified e-mail address // someone either tried to hijack this account or tried to register again with the same e-mail and succeeded foreach (AccountEmail email in account.AccountEmails) { if (IsStopping) break; IList verifiedemails = session.CreateCriteria(typeof(AccountEmail)) .Add(Expression.Eq("Verified", true)) .Add(Expression.Eq("Address", email.Address)) .SetMaxResults(1) .List(); if (verifiedemails.Count > 0) { // there exists another account that has the same address, verified // user has subscribed twice and verified another account bDelete = true; break; } } } if (account.AccountEmails != null && !bDelete) { foreach (AccountEmail email in account.AccountEmails) { if (IsStopping) break; // if we have never resent the e-mail confirmation, do it now if (email.Created == email.Modified) { ManagedAccountEmail mae = new ManagedAccountEmail(session, email); email.Modified = DateTime.UtcNow; session.Save(email); mae.Confirm(sec); } else if (email.Modified < DateTime.UtcNow.AddDays(-14)) { // we have sent another confirmation earlier than two weeks ago bDelete = true; break; } } } if (bDelete) { ma.Delete(ManagedAccount.GetAdminSecurityContext(session)); } session.Flush(); } catch (ThreadAbortException) { throw; } catch (Exception ex) { EventLogManager.WriteEntry(string.Format("Error processing reminder for account {0} ({1}): {2}", account.Id, account.Name, ex.Message), EventLogEntryType.Warning); } } }
public int ImportCampaignAccountLocation(string ticket, int campaign_id, string country, string state, string city) { int userid = ManagedAccount.GetAccountIdFromTicket(ticket); using (SnCore.Data.Hibernate.Session.OpenConnection()) { ISession session = SnCore.Data.Hibernate.Session.Current; ManagedSecurityContext sec = new ManagedSecurityContext(session, ticket); ITransaction trans = session.BeginTransaction(); AccountActivityQueryOptions options = new AccountActivityQueryOptions(); options.City = city; options.Country = country; options.State = state; options.PicturesOnly = false; options.BloggersOnly = false; int count = 0; try { IQuery query = session.CreateQuery(options.CreateQuery()); IEnumerator<Account> enumerator = query.Enumerable<Account>().GetEnumerator(); while (enumerator.MoveNext()) { ManagedAccount ma = new ManagedAccount(session, enumerator.Current); if (!ma.HasVerifiedEmail(sec)) continue; CampaignAccountRecepient existing = session.CreateCriteria(typeof(CampaignAccountRecepient)) .Add(Expression.Eq("Account.Id", ma.Id)) .Add(Expression.Eq("Campaign.Id", campaign_id)) .UniqueResult<CampaignAccountRecepient>(); if (existing != null) continue; ManagedCampaignAccountRecepient newrecepient = new ManagedCampaignAccountRecepient(session); TransitCampaignAccountRecepient newtransitrecepient = new TransitCampaignAccountRecepient(); newtransitrecepient.AccountId = ma.Id; newtransitrecepient.CampaignId = campaign_id; newtransitrecepient.Created = newtransitrecepient.Modified = DateTime.UtcNow; newtransitrecepient.Sent = false; newrecepient.CreateOrUpdate(newtransitrecepient, sec); count++; } trans.Commit(); SnCore.Data.Hibernate.Session.Flush(); } catch { trans.Rollback(); throw; } return count; } }
public int ImportCampaignAccountPropertyValues(string ticket, int campaign_id, int pid, string value, bool unset) { int userid = ManagedAccount.GetAccountIdFromTicket(ticket); using (SnCore.Data.Hibernate.Session.OpenConnection()) { ISession session = SnCore.Data.Hibernate.Session.Current; ManagedSecurityContext sec = new ManagedSecurityContext(session, ticket); ITransaction trans = session.BeginTransaction(); int count = 0; try { StringBuilder squery = new StringBuilder(); squery.Append( "SELECT {Account.*} FROM {Account} WHERE Account_Id IN (" + " SELECT Account.Account_Id FROM Account INNER JOIN AccountPropertyValue" + " ON Account.Account_Id = AccountPropertyValue.Account_Id" + " WHERE AccountPropertyValue.AccountProperty_Id = " + pid.ToString() + " AND AccountPropertyValue.Value LIKE '" + Renderer.SqlEncode(value) + "')"); if (unset) { squery.AppendFormat( " OR Account_Id NOT IN (" + " SELECT Account.Account_Id FROM Account INNER JOIN AccountPropertyValue" + " ON Account.Account_Id = AccountPropertyValue.Account_Id" + " AND AccountPropertyValue.AccountProperty_Id = {0}" + ")", pid); } ISQLQuery query = session.CreateSQLQuery(squery.ToString()) .AddEntity("Account", typeof(Account)); IList<Account> list = query.List<Account>(); foreach (Account account in list) { ManagedAccount ma = new ManagedAccount(session, account); if (!ma.HasVerifiedEmail(sec)) continue; CampaignAccountRecepient existing = (CampaignAccountRecepient)session.CreateCriteria(typeof(CampaignAccountRecepient)) .Add(Expression.Eq("Account.Id", ma.Id)) .Add(Expression.Eq("Campaign.Id", campaign_id)) .UniqueResult(); if (existing != null) continue; ManagedCampaignAccountRecepient newrecepient = new ManagedCampaignAccountRecepient(session); TransitCampaignAccountRecepient newtransitrecepient = new TransitCampaignAccountRecepient(); newtransitrecepient.AccountId = ma.Id; newtransitrecepient.CampaignId = campaign_id; newtransitrecepient.Created = newtransitrecepient.Modified = DateTime.UtcNow; newtransitrecepient.Sent = false; newrecepient.CreateOrUpdate(newtransitrecepient, sec); count++; } trans.Commit(); SnCore.Data.Hibernate.Session.Flush(); } catch { trans.Rollback(); throw; } return count; } }