Problems with React when using SignalR - javascript

I have the following code that I am implementing with SignalR:
Startup:
[assembly: OwinStartupAttribute("StartupConfiguration", typeof(AGENDA.Startup))]
namespace AGENDA
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableDetailedErrors = true;
hubConfiguration.EnableJavaScriptProxies = true;
app.MapSignalR();
}
}
}
Server:
It is where I create the various methods for capturing the server and can receive the information without any problem, however when I send the information from the client, it arrives empty.
public class MensajesHub : Hub
{
private EventModel _model;
private bool _modelUpdated = false;
public void UpdateModel(EventModel clientModel)
{
clientModel.LastUpdatedBy = Context.ConnectionId;
Clients.AllExcept(clientModel.LastUpdatedBy).UpdateMensaje(clientModel);
UpdateMensaje(clientModel);
}
public void UpdateMensaje(EventModel clientModel)
{
_model = clientModel;
_modelUpdated = true;
}
[HubMethodName("EnviarMensajes")]
public static void EnviarMensajes()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MensajesHub>();
context.Clients.All.updateMessages();
}
}
It is where I create the various methods for capturing the server and can receive the information without any problem, however when I send the information from the client, it arrives empty.
public class EventModel
{
[JsonProperty("id_cita")]
public long Id_Cita { get; set; }
[JsonProperty("descripcion_cita")]
public string Descripcion_Cita { get; set; }
[JsonProperty("start")]
public DateTime Start { get; set; }
[JsonProperty("end")]
public DateTime End { get; set; }
[JsonProperty("id_recurso")]
public long Id_Recurso { get; set; }
[JsonProperty("recurso_nombre")]
public string Recurso_Nombre { get; set; }
[JsonProperty("categoria")]
public int Categoria { get; set; }
[JsonIgnore]
public string LastUpdatedBy { get; set; }
}
Client:
I establish the connection with SignalR in this way, which is successful.
//SignalR Code
let mensajes = $.hubConnection();
//let mensajes = connection;
console.log(mensajes);
conexion = this.props.mensajes;
console.log(conexion);
conexion.start()
.done(function (model) {
conexion.logging = true;
console.log(conexion);
console.log('Now connected, connection ID=' + conexion.id);
updateServerModel();
})
.fail(function () {
conexion.hub.logging = false;
console.log(conexion);
console.log('Could not connect');
});
This is where I have the conflict, at first, it brings me the methods of the server, but I can not make the client to pass to the server.
function updateServerModel() {
console.log(conexion);
conexion.server.updateMensaje();
console.log(conexion);
conexion.server.updateModel();
console.log(conexion);
console.log(conexion.server);
console.log(conexion);
}
console.log(conexion);
//-------------------------------------
But the lines that say Server, never reaches anything, since it says that they are not a function
Any idea that this may happen ... ??? Could anyone help me with this ... ???
Thanks since now....!!!!

Related

I want to post a formdata with array of objects and image upload in react js application where i have asp.net core web api as my backed

I want to post formdata to my asp.net core web api backend where in the post request i have one image upload and 3 array of objects i need to post below is my post request model
public class PostProjectDto
{
public Guid Id { get; set; }
public string Code { get; set; }
public string ProjectName { get; set; }
public string Location { get; set; }
public Guid PropertyTypeId { get; set; }
public Guid OwnershipTypeId { get; set; }
public Guid RentTypeId { get; set; }
public long Duration { get; set; }
public long YearlyRent { get; set; }
public bool ElectricityIncluded { get; set; }
public bool WaterIncluded { get; set; }
public IFormFile File { get; set; }
public string ImageUrl { get; set; }
public List<PostElectricMeterDto> ElectricMeters { get; set; }
public List<PostWaterMeterDto> WaterMeters { get; set; }
public List<PostProjectFacilityRelation> ProjectFacilities { get; set; }
}
I am using CQRS pattern in backend where i have business logic written in application layer
public class Create
{
public class Command : IRequest<Result<Unit>>
{
public PostProjectDto Project { get; set; }
}
public class CommandValidator : AbstractValidator<Command>
{
public CommandValidator()
{
RuleFor(x => x.Project).SetValidator(new ProjectValidation());
}
}
public class Handler : IRequestHandler<Command, Result<Unit>>
{
private readonly DataContext _context;
private readonly IMapper _mapper;
private readonly IWebHostEnvironment _hostingEnvironment;
public Handler(DataContext context, IMapper mapper, IWebHostEnvironment hostingEnvironment)
{
_context = context;
_mapper = mapper;
_hostingEnvironment = hostingEnvironment;
}
public async Task<Result<Unit>> Handle(Command request, CancellationToken cancellationToken)
{
if(request.Project.File != null)
{
var fr = FileSystem.UploadFile(_hostingEnvironment, request.Project.File, new FileSystem.FileUploadSettings
{
FileType = FileSystem.FileType.Image,
StoragePath = LocalStorages.ProjectImageStoragePath
});
if (fr.IsSuccess)
{
request.Project.ImageUrl = fr.Result.ToString();
await _context.Projects.AddRangeAsync(_mapper.Map<Domain.Domains.Projects.Project>(request.Project));
var result = await _context.SaveChangesAsync(cancellationToken) > 0;
if (result)
{
if(request.Project.ElectricMeters.Count > 0 || request.Project.WaterMeters.Count > 0)
{
if (request.Project.ElectricMeters.Count > 0)
{
foreach (var item in request.Project.ElectricMeters)
{
await _context.AddAsync(_mapper.Map<Domain.Domains.Common.ElectricMeterNumber>(item));
}
}
if (request.Project.WaterMeters.Count > 0)
{
foreach (var item in request.Project.WaterMeters)
{
await _context.AddAsync(_mapper.Map<Domain.Domains.Common.WaterMeterNumber>(item));
}
}
var result2 = await _context.SaveChangesAsync(cancellationToken) > 0;
if (!result2) return Result<Unit>.Failure("Unable to add Project Features");
}
}
return Result<Unit>.Success(Unit.Value);
}
else
{
return Result<Unit>.Failure("Unable to add Project Image");
}
}
await _context.Projects.AddRangeAsync(_mapper.Map<Domain.Domains.Projects.Project>(request.Project));
var result1 = await _context.SaveChangesAsync(cancellationToken) > 0;
if (result1)
{
if (request.Project.ElectricMeters.Count > 0 || request.Project.WaterMeters.Count > 0)
{
if (request.Project.ElectricMeters.Count > 0)
{
foreach (var item in request.Project.ElectricMeters)
{
await _context.AddAsync(_mapper.Map<Domain.Domains.Common.ElectricMeterNumber>(item));
}
}
if (request.Project.WaterMeters.Count > 0)
{
foreach (var item in request.Project.WaterMeters)
{
await _context.AddAsync(_mapper.Map<Domain.Domains.Common.WaterMeterNumber>(item));
}
}
var result2 = await _context.SaveChangesAsync(cancellationToken) > 0;
if (!result2) return Result<Unit>.Failure("Unable to add Project Features");
}
}
if (!result1) return Result<Unit>.Failure("Unable to add Project");
return Result<Unit>.Success(Unit.Value);
}
}
}
Below is my endpoint
[HttpPost]
public async Task<IActionResult> CreateProject([FromForm]PostProjectDto Project)
{
return HandleResult(await Mediator.Send(new Create.Command { Project = Project }));
}
i am sending a formdata from the react application
const onFinish =(values)=>{
//Change the formdata to normal request remove the image upload in post request of project and make the image upload seperate
const formdata= new FormData()
formdata.append("id", projectId)
formdata.append("code",values.code)
formdata.append("projectName",values.projectName)
formdata.append("waterMeters", JSON.stringify(waterMeters)) \\ array of objects
formdata.append("electricMeters", JSON.stringify(electricMeters)) \\ array of objects
formdata.append("projectFacilities",JSON.stringify(facilitedAdded)) \\ array of objects
if(values.file) formdata.append("file", projectImage)
formdata.append("propertyTypeId", values.propertyTypeId)
formdata.append("ownershipTypeId", values.ownershipTypeId)
formdata.append("rentTypeId", values.rentTypeId)
formdata.append("duration", Number(values.duration))
formdata.append("yearlyRent", Number(values.yearlyRent))
formdata.append("electricityIncluded", electricityIncluded)
formdata.append("waterIncluded", waterIncluded)
formdata.append("location", values.location)
agent.Project.create(formdata).then(res=> projectform.resetFields())
console.log("submitted value", Object.fromEntries(formdata))
}
i am using axios for api requests
create:async (data)=> await axios.post('Project',data,{headers: { 'Content-type': 'multipart/form-data' }}).then(res=>{
if(res.status==200) message.success("Added Project Successfully")
}).catch(function(err){
const error = err.toJSON()
if(error.status === 500){
message.error("Unable to Add Project!")
}
})
But the problem is iam not getting the array at the endpoint the count is always zero and i am not able to store it

How to send data from react to Controller in ASP.NET MVC?

I am new to react. I am trying to build a CRUD application with React and .NET MVC. I am able to find the code for only getting content from controller, but not for posting.
Below is the code for getting data from controller:
var App = React.createClass({
getInitialState: function(){
return{data: ''};
},
componentWillMount: function(){
var xhr = new XMLHttpRequest();
xhr.open('get', this.props.url, true);
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
this.setState({ data: response.result });
}.bind(this);
xhr.send();
},
render: function(){
return(
<h1>{this.state.data}</h1>
);
}
});
Please provide me the code to send data from react to controller.
My data class:
public partial class EmployeeTable
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Designation { get; set; }
public long Salary { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
As mentioned in the comments, sent the data using How to make a rest post call from ReactJS code?
Now create an action in your controller
[HttpPost]
public void GetInfo([FromBody]EmployeeTable data){
}

Service Return Empty Lists To Api Controller

I am working in service fabrics micro services , where i need to fetch record for an object. when I send request to API , it shows me empty lists while rest of the data is in place. while debugging I came to know that before returning to API controller my service object has all the data expected i.e lists has data , but when it comes back to web API the lists are empty.
After searching for solution over web I came to know that every time a request is to the API the lists are recreated , so it shows empty result. Any Solutions to come out of this problem?
Here is my piece of code.
The following Is the Web Api Method.
[HttpGet()]
[Route("edit/{readingListId}")]
[ProducesResponseType(typeof(List<GetReadingListDTO>), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(List<GetReadingListDTO>), (int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetReadingListById(int readingListId)
{
try
{
var readingList = await this._readingListService.GetReadingListByIdAsync(readingListId);
return Ok(readingList);
}
catch (Exception ex)
{
this._logger.LogError(ex.Message);
return BadRequest();
}
}
The following Is the Service Method.
public async Task<Domain.ReadingList> GetReadingListByIdAsync(int readingListId)
{
try
{
Domain.ReadingList readingList = await _repository.FindById(readingListId);
return readingList;
}
catch (Exception ex)
{
throw;
}
}
Moreover , This Is My Entity.
public class ReadingList : EntityBase, IAggregateRoot, IAggregateCreateRoot, IAggergateUpdateRoot, IAggregateDeleteRoot
{
public ReadingList()
{
this.Items = new List<ReadingListItem>();
this.Assignees = new List<ReadingListAssignee>();
}
public int Id { get; set; }
public EntityType EntityTypeId { get; set; }
public int EntityId { get; set; }
public string Title { get; set; }
public DateTime CompletionDate { get; set; }
public int ReminderDay { get; set; }
public string ReminderDayType { get; set; }
public bool SendReminder { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public int? UpdatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
public int? DeletedBy { get; set; }
public DateTime? DeletedDate { get; set; }
public bool? Deleted { get; set; }
public List<ReadingListItem> Items { get; private set; }
public List<ReadingListAssignee> Assignees { get; private set; }
}
Thanks!
Edited
The Issue Was Resolved , By Simply Changing The dll Versions.One Of The Service Had And Old Version While The Version Was Updated In The Other One.
Thanks For The Help.

Passing JavaScript object to C#

I am trying to create a new row in a table I have hosted in Azure SQL Database. My front end is AngularJS with C# in .NET as the back end.
Here is my code from the front end passing the object:
var insertTicket = function (newTicket) {
return $http.post("http://localhost:50412/api/tickets", JSON.stringify(newTicket))
.then(function (response) {
console.log(response);
console.log("Insert Successful");
return;
});
And here is my backend code that receives the data and tries to add to the database:
[Route("api/tickets")]
public HttpResponseMessage Post(Ticket t)
{
TicketsRepository.InsertTicket(t);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
In TicketRepisitory:
public static void InsertTicket(Ticket tick)
{
var maxID = (from ticket in dataContext.Tickets
select ticket.id).Max();
var tick = new Ticket();
tick.id = maxID + 1;
dataContext.Tickets.Add(tick);
dataContext.SaveChanges();
}
And Here is my Ticket class:
public partial class Ticket
{
//Properties
public int id { get; set; }
public string title { get; set; }
public string customer { get; set; }
public string barcode { get; set; }
public string assignedTo { get; set; }
public string category { get; set; }
public string importance { get; set; }
public Nullable<System.DateTime> openDate { get; set; }
public Nullable<System.DateTime> dueDate { get; set; }
public Nullable<System.DateTime> closedDate { get; set; }
public string comments { get; set; }
public string condition { get; set; }
public Nullable<int> workHours { get; set; }
//Relationships
public Employee Employee { get; set; }
public Employee Employee1 { get; set; }
public Equipment Equipment { get; set; }
}
I think the issue is with Post() expecting a ticket object. I have tried searching for how to receive JSON data and use that for Ticket, but with out much luck.
My Problem is that I can not create a new row. No changes are reflected in my database.
You don't need to JSON.stringify your object when POSTing data with $httpin AngularJS, just pass the object itself as the second parameter, like this:
var insertTicket = function (newTicket) {
return $http.post("http://localhost:50412/api/tickets", newTicket)
.then(function (response) {
console.log(response);
console.log("Insert Successful");
return;
});
First there is no need to call JSON.stringify() method on newticket javascript object for second paramter of $http.post() method.
Then in the web api method write a parameter of type JObject with the name newTicket to receive the posted object, and use generic version of ToObject method to convert posted data to desired type. Don't forget to use [FromBody] attribute for the method parameter. the code for webapi looks like this:
[Route("api/tickets")]
public HttpResponseMessage Post([FromBody]JObject newTicket)
{
var t = newTicket.ToObject<Ticket>();
TicketsRepository.InsertTicket(t);
HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
return response;
}

Breeze.js /NET+EF complex object behaviors rather strange

I’m developing a custom data access layer to be consumed in breeze.js
What I have:
The Model:
public class Product
{
[Key]
public int ProductId { get; set; }
public string Upc { get; set; }
public string Name { get; set; }
public decimal MsrpPrice { get; set; }
public int Quantity { get; set; }
public virtual ICollection<ProductFeature> Features { get; set; }
public virtual B2BCategory InB2BCategory { get; set; }
public virtual ICollection<ImageDescriptor> Images { get; set; }
public int CategoryId {get; set;}
}
public class ProductFeature
{
public int ProductId { get; set; }
public string Name { get; set; }
public string GroupName { get; set; }
public string Operation { get; set; }
public decimal Value { get; set; }
}
public class ImageDescriptor
{
public int ProductId { get; set; }
public string Uri { get; set; }
public DateTime Updated { get; set; }
public bool IsDefault { get; set; }
}
The Context Provider:
public class ProductContextProvider : ContextProvider
{
private readonly ProductRepository repo =new ProductRepository();
public IQueryable<B2BCategory> Categories
{
get { return repo.Categories.AsQueryable(); }
}
public IQueryable<Product> Products
{
get
{
return repo.Products.OrderBy(p => p.ProductId).AsQueryable();
}
}
protected override string BuildJsonMetadata()
{
var contextProvider = new EFContextProvider<ProductMetadataContext>();
return contextProvider.Metadata();
}
protected override void SaveChangesCore(SaveWorkState saveWorkState)
{…
}
// No DbConnections needed
public override IDbConnection GetDbConnection()
{
return null;
}
protected override void OpenDbConnection()
{
// do nothing
}
protected override void CloseDbConnection()
{
// do nothing
}
}
internal class ProductMetadataContext : DbContext
{
static ProductMetadataContext()
{
Database.SetInitializer<ProductMetadataContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ProductFeatureConfiguration());
modelBuilder.Configurations.Add(new ImageDescriptorConfiguration());
}
public DbSet<Product> Products { get; set; }
public DbSet<B2BCategory> Categories { get; set; }
}
internal class ImageDescriptorConfiguration : EntityTypeConfiguration<ImageDescriptor>
{
public ImageDescriptorConfiguration()
{
// I tried to mess up with key orders
HasKey(i => new { i.Uri, i.ProductId});
}
}
internal class ProductFeatureConfiguration : EntityTypeConfiguration<ProductFeature>
{
public ProductFeatureConfiguration()
{
HasKey(f => new { f.ProductId, f.Name });
}
}
I’m stuffing the Features and Images properties of a Product directly:
product.Features = new Collection<ProductFeature>();
product.Images = new Collection<ImageDescriptor>();
…
var imgd = new ImageDescriptor
{
ProductId = product.ProductId,
Updated = DateTime.Now,
Uri = defsmall,
IsDefault = !product.Images.Any()
}
product.Images.Add(imgd);
…
var pf = new ProductFeature
{
ProductId = product.ProductId,
GroupName = "Size",
Name = size,
Value = size == "Small" ? new decimal(.75):size == "Medium" ? new decimal(1.3):new decimal(1.8),
Operation = "*"
};
product.Features.Add(pf);
Totally there are, say, 3 product features and 2 images per product item.
In the client side I query this like:
return entityQuery.from('Products').using(EntityManager).execute();
And… I’ve got the very strange thing:
The images property contains an empty array, the features property contains an array of 5!!! elements – 3 of type ProductFeature and 2 of type ImageDescriptor.
I think this is a bug – could you help me, please?
I don't see any code that creates a breeze EntityManager and adds or attaches your newly created entities and then saves them. Please take a look at the Breeze examples in the downloadable zip from the BreezeJs website.

Categories

Resources