tron.net.client: How to Get Account Balance - tron

I am try to get the balance from a random account (I think the most valuable account) in the mainnet. But it always return 0.
May I know what is wrong with my code?
internal class MainCfg : IChannelConfiguration
{
public int Port { get; set; } = 50051;
public string Host { get; set; } = "3.225.171.164"; // Correct?
public int? MaxConcurrentStreams { get; set; } = 2;
public TimeSpan? TimeOutMs { get; set; } = TimeSpan.FromSeconds(5);
}
var configuration = new MainCfg();
var grpcChanngelFactory = new GrpcChannelFactory(configuration);
var walletClientFactory = new WalletClientFactory(grpcChanngelFactory);
var wallet = new Wallet(walletClientFactory, new AllClientsDefaultCallConfiguration());
var bytes = Base58.Decode("TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR"); // An account with lots of balance
var account = await w.GetAccountAsync(new Tron.Net.Protocol.Account{
Address = ByteString.CopyFrom(bytes)
});
Console.Write("Balance=" + account.Balance); // output = 0

Related

ASP.NET CORE Web API - Payment notification Email Scheduler using Hangfire Cron Job

I have a Payment Application in ASP.NET Core-6 Web API Entity Framework. I have this model:
Payment:
public class Payment
{
public Guid Id { get; set; }
public string ReferenceNumber { get; set; }
public string Email { get; set; }
public DateTime TransactionDate { get; set; }
public DateTime? DueDate { get; set; }
public decimal Amount { get; set; }
}
EmailSettings:
public class EmailSettings
{
public string Username { get; set; }
public string Password { get; set; }
public string DisplayName { get; set; }
public string Host { get; set; }
public int Port { get; set; }
}
EmailService:
public async Task<string> SendEmailAsync(List<string> ToEmailName, string Subject, EventModel Data)
{
_mailResponse = string.Empty;
using (SmtpClient smtpClient = new SmtpClient(_mailConfig.Host, _mailConfig.Port))
{
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new NetworkCredential(_mailConfig.Username, _mailConfig.Password);
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.SendCompleted += new SendCompletedEventHandler((object sender, AsyncCompletedEventArgs e) =>
{
_mailResponse = (e.Error != null || e.Cancelled != false) ? "failure" : "success";
});
MailMessage message = new MailMessage
{
From = new MailAddress(_mailConfig.Username, _mailConfig.DisplayName),
Subject = Subject,
SubjectEncoding = Encoding.UTF8,
BodyEncoding = Encoding.UTF8,
HeadersEncoding = Encoding.UTF8,
IsBodyHtml = true,
Body = GetEmailContent(Subject, Data),
Priority = MailPriority.High
};
foreach (string EmailName in ToEmailName)
{
message.To.Add(new MailAddress(EmailName));
}
await smtpClient.SendMailAsync(message);
}
return _mailResponse;
}
I am using HangFire.
I want the application to run a schedule using HangFire, and iterate the Payment Model using ReferenceNumber and DueDate. Then send email notification to the affected Email, 14 days to the DueDate. Reminding the affected users that his payment should be done on the DueDate
How do I achieve this?
Thanks
This can be done by scheduling notification directly based on DueDate - 14 days (or current date if that is less than 14 days away).
Also probably you would need to some extra check to your notification to see if that has already been paid before sending a reminder.
BackgroundJob.Schedule(
() => NotficationService.SendPaymentNotificationEmail(Payment.Id),
TimeSpan.FromDays(DueDate.AddDays(-14)));
Reference:
https://docs.hangfire.io/en/latest/background-methods/calling-methods-with-delay.html

getting 400 error on webapi call blazorserver

i am trying to setup a blazor server app, calling a webapi.
I keep getting a 400 error returned, when I call the API.
I have 3 Projects, projectserver and projectapi. projectserver is where the Blazor app sits and Project API is where the API sits.
I don't know if the apicall can find the API as it does not hit any breakpoints in the API section, I am totally confused, as if it cannot find the API then it should return a 404 or other error and not 400 ?
thank you for your efforts.
this is my code,
Projectserver, this is where I post the Register Model to the API
public string message { get; set; }
public RegisterModel r = new RegisterModel();
private async Task Create(MouseEventArgs e)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(r);
var client = clientfactory.CreateClient("ServerApi");
var result = await client.PostAsJsonAsync("/Account/Register",json); // check the Startup file and check base address for the Full route.
message = result.StatusCode.ToString();
}
}
the ClientFactory returns the base address of what is defined in startup.cs
services.AddHttpClient("ServerApi", client => client.BaseAddress = new Uri("https://localhost:44302/"));
the API is Projectserver and defined as follows.
[Route("[controller]")]
[ApiController]
public class AccountContoller : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly SecurityOptions _securityOptions;
private readonly JwtIssuerOptions _jwtOptions;
// GET: api/<Account>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<Account>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<Account>
[HttpPost]
public void Post([FromBody] string value)
{
}
// POST api/<Account>
[HttpPost("Register")]
public async Task<ActionResult<RegisterResult>> Register(RegisterModel model)
{
RegisterResult r = new RegisterResult();
var Exisits = await _context.Users.Where(r => r.EmailAddress == model.Email).FirstOrDefaultAsync();
if(Exisits != null)
{
r.Sucsess = false;
r.ErrorMessage = "Email - Already Exisits";
return r;
}
else
{
try
{
User newuser = new User();
newuser.CreatedDateTime = DateTime.UtcNow;
newuser.UserID = Guid.NewGuid();
newuser.MobileNumber = model.MobileNumber;
newuser.Password = model.Password;
newuser.FirstName = model.FirstName;
newuser.Surname = model.LastName;
_context.Users.Add(newuser);
await _context.SaveChangesAsync();
r.Sucsess = true;
return r;
}
catch(Exception e)
{
r.Sucsess = false;
r.ErrorMessage = e.ToString();
return r;
}
}
}
the Model classes are defined as Serializable
[Serializable]
public class RegisterResult
{
public bool Sucsess { get; set; }
public string ErrorMessage { get; set; }
}
[Serializable]
public class RegisterModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string RoleID { get; set; }
public string EntityID { get; set; }
public string MobileNumber { get; set; }
}
Can you please modify your code as below and give it a try:-
var serializedBody = JsonConvert.SerializeObject(r);
var jsonRequestBodyContent = new StringContent(serializedBody, Encoding.UTF8,"application/json");
var client = clientfactory.CreateClient("ServerApi");
var result = await client.PostAsync("/Account/Register",jsonRequestBodyContent);

Update Value Object fileld in Mvc code First

I have a value object named Validity and its attribute StartDate and EndDate.
I have Update this field.but getting some error.The error is:
InvalidOperationException: The entity type 'Validity' has a defining navigation and the supplied entity is currently not being tracked. To start tracking this entity call '.Reference().TargetEntry' on the owner entry.
How to solve this error?
My Code Is:
public async Task<Subscription> Update(string ID, bool Active, string Plan, string Periodicity, decimal Price, string LocationTargets, string paymentStatus,
DateTime startDate, DateTime endDate, string OperationType)
{
#region PaymentStatus
int EnumPaymentStatus = 0;
string[] values = Enum.GetNames(typeof(PaymentStatusEnum.PaymentStatus));
if (values[0] == paymentStatus)
{
EnumPaymentStatus = (int)PaymentStatus.Due;
}
else if (values[1] == paymentStatus)
{
EnumPaymentStatus = (int)PaymentStatus.Open;
}
else if (values[2] == paymentStatus)
{
EnumPaymentStatus = (int)PaymentStatus.UnPaid;
}
else if (values[3] == paymentStatus)
{
EnumPaymentStatus = (int)PaymentStatus.Paid;
}
#endregion
#region Periodicity
int EnumPeriodicityValue = 0;
string[] values1 = Enum.GetNames(typeof(PeriodicityEnum.EnumPeriodicity));
if (values1[0] == Periodicity)
{
EnumPeriodicityValue = (int)EnumPeriodicity.Monthly;
}
else if (values1[1] == Periodicity)
{
EnumPeriodicityValue = (int)EnumPeriodicity.Trimestral;
}
else if (values1[2] == Periodicity)
{
EnumPeriodicityValue = (int)EnumPeriodicity.Semestral;
}
else if (values1[3] == Periodicity)
{
EnumPeriodicityValue = (int)EnumPeriodicity.Annual;
}
#endregion
#region Operation Type
int OperationTypeValue = 0;
string[] values2 = Enum.GetNames(typeof(OperationTypeEnum.EnumOperationType));
if (values2[0] == OperationType)
{
OperationTypeValue = (int)EnumOperationType.NewSubscription;
}
else if (values2[1] == OperationType)
{
OperationTypeValue = (int)EnumOperationType.SubscriptionRenewal;
}
else if (values2[2] == OperationType)
{
OperationTypeValue = (int)EnumOperationType.SubscriptionCancellation;
}
else if (values2[3] == OperationType)
{
OperationTypeValue = (int)EnumOperationType.SubscriptionChange;
}
#endregion
#region Update Data in Subscription Table
var subscription = new Subscription()
{
ID = ID,
Active = Active,
Plan = Plan,
Periodicity = Convert.ToString(EnumPeriodicityValue),
Price = Price,
LocationTargets = LocationTargets,
PaymentStatus = Convert.ToString(EnumPaymentStatus),
OperationType = Convert.ToString(OperationTypeValue),
UpdatedAt = DateTime.UtcNow
};
subscription.Validity = new Validity(startDate, endDate);
//Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<Subscription> s = await _db.AddAsync(subscription);
_db.Entry(subscription).Property(x => x.Active).IsModified = true;
_db.Entry(subscription).Property(x => x.Plan).IsModified = true;
_db.Entry(subscription).Property(x => x.Periodicity).IsModified = true;
_db.Entry(subscription).Property(x => x.Price).IsModified = true;
_db.Entry(subscription).Property(x => x.LocationTargets).IsModified = true;
_db.Entry(subscription).Property(x => x.PaymentStatus).IsModified = true;
_db.Entry(subscription.Validity).Property(x => x.StartDate).IsModified = true;
_db.Entry(subscription.Validity).Property(x => x.EndDate).IsModified = true;
_db.Entry(subscription).Property(x => x.OperationType).IsModified = true;
_db.Entry(subscription).Property(x => x.UpdatedAt).IsModified = true;
#endregion
#region Insert Data in SubscriptionHistory Table
string a = Convert.ToString(GuidComb.Generate());
var subscriptionhistory = new SubscriptionHistory()
{
ID = a,
Active = Active,
Plan = Plan,
Periodicity = Convert.ToString(EnumPeriodicityValue),
Price = Price,
LocationTargets = LocationTargets,
PaymentStatus = Convert.ToString(EnumPaymentStatus),
OperationType = Convert.ToString(OperationTypeValue)
};
subscriptionhistory.Validity = new Validity(startDate, endDate);
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<SubscriptionHistory> y = await _db.AddAsync(subscriptionhistory);
#endregion
await _db.SaveChangesAsync();
return subscription;
}
In Subscription Class:
public class Subscription: BaseEntity
{
public Subscription()
{
this.ID = Convert.ToString(System.Guid.NewGuid());
this.CreatedAt = DateTime.UtcNow;
this.IsCancel = false;
}
private List<Validity> validities = new List<Validity>();
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[MaxLength(128)]
public string ID { get; set; }
public bool Active { get; set; }
[MaxLength(150)]
public string Plan { get; set; }
[MaxLength(101)]
public string Periodicity { get; set; }
public decimal Price { get; set; }
[MaxLength(250)]
public string LocationTargets { get; set; }
[MaxLength(101)]
public string PaymentStatus { get; set; }
public Validity Validity { get; set; }
[MaxLength(101)]
public string OperationType { get; set; }
public bool IsCancel { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public DateTime DeletedAt { get; set; }
public bool Deleted { get; set; }
//private List<Validity> validities = new List<Validity>();
public void Assignvalidity(Validity validitys)
{
this.validities.Add(validitys);
}
}
In Validity Class:
public class Validity : ValueObject
{
public DateTime StartDate { get; private set; }
public DateTime EndDate { get; private set; }
private Validity() { }
public Validity(DateTime startdate, DateTime enddate)
{
StartDate = startdate;
EndDate = enddate;
}
protected override IEnumerable<object> GetAtomicValues()
{
yield return StartDate;
yield return EndDate;
}
}
Add this line:
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry s = _db.Update(subscription);
After this line:
subscription.Validity = new Validity(startDate, endDate);
In order to update an entity it must be tracked by the entity, in your below code you are creating new object :
var subscription = new Subscription()
{
ID = ID,
Active = Active,
Plan = Plan,
Periodicity = Convert.ToString(EnumPeriodicityValue),
Price = Price,
LocationTargets = LocationTargets,
PaymentStatus = Convert.ToString(EnumPaymentStatus),
OperationType = Convert.ToString(OperationTypeValue),
UpdatedAt = DateTime.UtcNow
};
First you need to get that entity from the db, then update related fields and save to db;
[UPDATE]
The validity is a related entity to Subscription, so you need an include query to fetch the object from the db, then you can update and save.
var subscription = _db.Set<Subscription>().Single(x=>x.ID == ID).Include(x=>x.Validity);
subscription.Validity.StartDate = startDate;
subscription.Vaklidity.EndDate = endDate;
_db.SaveChanges();
[UPDATE]
add foreignkey attributes then create a new migration then update the db:
public class Validity : ValueObject
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string SubscriptionID { get; set; }
public Subscription Subscription { get; set; }
// ...
}
public class Subscription: BaseEntity
{
public string ValidityID { get; set; }
public Validity Validity { get; set; }
// ...
}
After updating the db, get the related Validity entity and update it:
var validity = _db.Set<Validity>().Find(x => x.SubscriptionID == ID);
validity.StartDate = startDate;
validity.EndDate = endDate;
_db.SaveChanges();

Retrieve values from SQL database - EF

I'm trying to figure out how to pull values from a SQL database and display this in a razor view.
I have the following class using Entity Framework (I believe)
public class EventLog
{
[Key]
public int Id { get; set; }
public int EventId { get; set; }
public int MaxDelegates { get; set; }
public string Code { get; set; }
public DateTime End { get; set; }
public string Title { get; set; }
}
And I want to map title to DBTitle in the following model:
public class CourseDetailVM : CourseDetailSummaryVM
{
public EventLog DBTitle { get; set; }
}
I then want to see this in the following view:
#using TSW.Web.Helpers
#model TSW.Web.ViewModels.CourseDetailVM
#{
Layout = "~/Views/_Master.cshtml";
}
#Model.DBTitle.Title;
I have the following controller already in place (sorry for the length I plan to reduce this down):
public class CourseDetailController : BaseRenderController<CourseDetailPageDT>
{
private readonly ISitePageFactory _pageFactory = null;
private readonly IEventService _eventService = null;
public CourseDetailController(IEventService eventService, ISitePageFactory pageFactory)
{
_pageFactory = pageFactory;
_eventService = eventService;
}
public async Task<ActionResult> CourseDetail()
{
var homepage = _pageFactory.GetCurrentHomepage();
var model = Mapper.Map<CourseDetailVM>(CurrentContent);
model.Email = homepage.ContactEmail;
model.PhoneNumber = homepage.HeaderPhoneNumber;
model.InnerPageHeader.ShowHeading = true;
model.InnerPageHeader.Title = model.PageTitle;
if (model.Categories.Count == 1)
{
var categoryTagId = model.Categories.First().Id;
var contentTypeAlias = DocumentTypeHelper.GetDocumentTypeAlias<CourseListingPageDT>();
var courseCategoryPage = Umbraco.TypedContentAtXPath($"//{contentTypeAlias}")
.FirstOrDefault(x => x.GetPropertyValue<int>(Constants.DocumentTypes.CourseListingPage.Category) == categoryTagId);
if (courseCategoryPage != null)
{
model.InnerPageHeader.BackLink = Mapper.Map<LinkItem>(courseCategoryPage.Id);
}
}
try
{
model.Events = await _eventService.GetEventsForCourse(CurrentContent.AdministrateId);
}
catch (Exception ex)
{
model.Events = new StaticPagedList<Event>(Enumerable.Empty<Event>(), 1, 1, 0);
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
if (CurrentContent.Graphic != 0)
{
model.InnerPageHeader.Graphic = Mapper.Map<CtaItem>(CurrentContent.Graphic);
}
return View(model);
}
}
I've tried every suggestion I can google to add the mapping in the controlling but can't get my head around this simple function of pulling the value from a SQL database into the razor view.
Could anyone help me out?

inserting data in database table in one to many relationship in code first

I am using Code First Approach with Mvc4.For authentication and authorization, simple membership is being used.
My UserProfile class have these fields where a user can have multiple posts and comments.
[Table("UserProfile")]
public class UserProfile
{
public UserProfile()
{
this.PostComments = new HashSet<PostComment>();
this.Posts = new HashSet<Post>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string AvatarExt { get; set; }
public virtual ICollection<PostComment> PostComments { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
and my Post class is something like this.here i have configured one to many relationship between userprofile class and Post class.
public class Post
{
public Post()
{
this.PostComments = new HashSet<PostComment>();
}
[Key]
public int PostId { get; set; }
public string Message { get; set; }
public int PostedBy { get; set; }
public System.DateTime PostedDate { get; set; }
public virtual ICollection<PostComment> PostComments { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
and this is my controller's action method for adding posts to the post table in the database.
public HttpResponseMessage PostPost(Post post)
{
post.PostedBy = WebSecurity.CurrentUserId;
post.PostedDate = DateTime.UtcNow;
// post.UserProfile.UserId = WebSecurity.CurrentUserId;
ModelState.Remove("post.PostedBy");
ModelState.Remove("post.PostedDate");
// ModelState.Remove("post.UserProfile.UserId");
if (ModelState.IsValid)
{
db.Posts.Add(post);
db.SaveChanges();
var usr = db.UserProfiles.FirstOrDefault(x => x.UserId == post.PostedBy);
var ret = new
{
Message = post.Message,
PostedBy = post.PostedBy,
PostedByName = usr.UserName,
PostedByAvatar = imgFolder + (String.IsNullOrEmpty(usr.AvatarExt) ? defaultAvatar : post.PostedBy + "." + post.UserProfile.AvatarExt),
PostedDate = post.PostedDate,
PostId = post.PostId
};
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ret);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = post.PostId }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
when i tried to debug this action method, i found out that it is passing null at this line---
PostedByName = usr.UserName
what should i do to pass current loggedIn userName to the database.
One more information i want to share is--
In Sql Server, it is creating 5 columns----
PostId(which is primary key),
Message,PostedBy(int),PostedDate, UserProfile_UserId(Foreign key column).
Now, everything is working fine but in UserProfile_UserId column, it is storing null.
I know it should not be null but how.
What i am missing.what should i do.There was slight change in this code using dbFirst approach, and that code is working fine.
To get post on the view page, action method is----
public dynamic GetPosts()
{
var ret = (from post in db.Posts.ToList()
orderby post.PostedDate descending
select new
{
Message = post.Message,
PostedBy = post.PostedBy,
PostedByName = post.UserProfile.UserName,
PostedByAvatar = imgFolder + (String.IsNullOrEmpty(post.UserProfile.AvatarExt) ? defaultAvatar : post.PostedBy + "." + post.UserProfile.AvatarExt),
PostedDate = post.PostedDate,
PostId = post.PostId,
PostComments = from comment in post.PostComments.ToList()
orderby comment.CommentedDate
select new
{
CommentedBy = comment.CommentedBy,
CommentedByName = comment.UserProfile.UserName,
CommentedByAvatar = imgFolder + (String.IsNullOrEmpty(comment.UserProfile.AvatarExt) ? defaultAvatar : comment.CommentedBy + "." + comment.UserProfile.AvatarExt),
CommentedDate = comment.CommentedDate,
CommentId = comment.CommentId,
Message = comment.Message,
PostId = comment.PostId
}
}).AsEnumerable();
return ret;
}
this is the action method where i want to show post and comment with their UserName.here, PostedByName is returning null.