my code is
public class BaseDTO
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class DataDTO : BaseDTO
{
public int Level { get; set; }
public DateTime ChangedDate { get; set; }
}
I call web-api by httpclient
static void Main(string[] args)
{
var httpClientHandler = new HttpClientHandler();
httpClientHandler.UseDefaultCredentials = true;
var client = new HttpClient(httpClientHandler);
client.BaseAddress = new Uri("http://localhost/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var dto = new DataDTO()
{
Id = 1,
Code = "a",
Name = "A",
Level = 10,
ChangedDate = DateTime.Now
};
HttpResponseMessage resp =
client.PostAsJsonAsync(
"api/MyApi/Creat", dto).Result;
if (resp.IsSuccessStatusCode)
{
}
}
when i debug,i found the data that server received ,"Id","Code" and "Name" inherited from base class were all null,"Level" and "ChangedDate" were right.
I googled,but I cannot find my reason.
changed to use restsharp,it works well
Related
i have the following client model that has a relation with orders and BloodType tables:
public partial class Client
{
public Client()
{
ClientOrders = new HashSet<ClientOrder>();
}
public long ClientId { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public long BloodTypeId { get; set; }
public virtual BloodType BloodType { get; set; }
public virtual ICollection<ClientOrder> ClientOrders { get; set; }
}
when i try the following code to lazy load the orders and the BloodType it's not rendering them and it return the as empty list and null value.
here's my code:
[HttpGet]
[Route("clients-orders")]
public async Task<IActionResult> GetClientsOrders()
{
try
{
var result = await _trainingContext.Clients.FromSqlRaw("Exec getClients").ToListAsync();
var clientsOrders = new List<Client>();
foreach (var client in result)
{
Client currentClient = new Client()
{
ClientId = client.ClientId,
BloodTypeId = client.BloodTypeId,
PhoneNumber = client.PhoneNumber,
ClientOrders = client.ClientOrders,
BloodType = client.BloodType
};
clientsOrders.Add(currentClient);
}
return Ok(clientsOrders);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
Any solution would be very appreciated,
Thank you!
I am trying to call the Azure DevOps Release Api to create a release from c# code, but it is giving me 400 Bad request error.
I am using the example in the following link by Microsoft
https://learn.microsoft.com/en-us/rest/api/azure/devops/release/releases/create?view=azure-devops-rest-5.1
Here is my code .....
My application is a small console app.
namespace DevOpsReleasePipelineTest
{
public class InstanceReference
{
public string id { get; set; }
public IList<string> name { get; set; }
public string definitionId { get; set; }
}
public class Artifacts
{
public string alias { get; set; }
public InstanceReference instanceReference { get; set; }
}
public class Application
{
public int definitionId { get; set; }
public string description { get; set; }
public IList<Artifacts> artifacts { get; set; }
public bool isDraft { get; set; }
public string reason { get; set; }
public IList<object> manualEnvironments { get; set; }
}
}
private static Application GetPayLoad()
{
InstanceReference instanceReference = new InstanceReference();
instanceReference.id = "7874";
instanceReference.name = null;
instanceReference.definitionId = "7874";
List<Artifacts> artifacts = new List<Artifacts>();
Artifacts artifacts1 = new Artifacts();
artifacts1.alias = "Mobility-Dev";
artifacts1.instanceReference = instanceReference;
artifacts.Add(artifacts1);
Application application = new Application();
application.definitionId = 4;
application.description = "Creating Sample release";
application.isDraft = false;
application.reason = "test";
application.manualEnvironments = null;
application.artifacts = artifacts;
return application;
}
public static async Task<HttpResponseMessage> PostRelease()
{
var personalaccesstoken = "djhghgtydfhfgdyuftyftdsf";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var payLoad = GetPayLoad();
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(payLoad),
Encoding.UTF8, "application/json");
Task <HttpResponseMessage> response = client.PostAsync("https://xxx-
devops.vsrm.visualstudio.com/DemoProj/_apis/release/releases?api-version=5.1", httpContent);
var result = await response;
return result;
}
Your code does not work on my side and I`ve checked the url. There is some problem %)
Try to use the url format from documentation:
POST https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases?api-version=5.1
Additionally, you can check the error in your response:
var response = client.PostAsync("https://vsrm.dev.azure.com/<org>/<team_project>/_apis/release/releases?api-version=5.1", httpContent).Result;
if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
{
string message = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(message);
}
My example:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace EventsCoreApi.Models.Entities
{
public partial class Event
{
public Event()
{
EventHasMusicGenre = new HashSet<EventHasMusicGenre>();
}
public uint EventId { get; set; }
public string Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[Timestamp]
public byte[] StartTime { get; set; }
[Timestamp]
public byte[] EndTime { get; set; }
public string Description { get; set; }
public string PolicyMinimumAge { get; set; }
public string PolicyDescription { get; set; }
public uint DressCodeId { get; set; }
public virtual DressCode DressCode { get; set; }
public virtual ICollection<EventHasMusicGenre> EventHasMusicGenre { get; set; }'
[HttpPost]
public async Task<ActionResult<Event>> PostEvent(EventDto eventFromClient)
{
var newEvent = new Event
{
Name = eventFromClient.Name,
StartDate = eventFromClient.StartDate,
EndDate = eventFromClient.EndDate,
StartTime = eventFromClient.StartTime,
EndTime = eventFromClient.StartTime,
Description = eventFromClient.Description,
DressCodeId = eventFromClient.DressCodeId,
PolicyMinimumAge = eventFromClient.PolicyMinimumAge,
PolicyDescription = eventFromClient.PolicyDescription
};
_context.Event.Add(newEvent);
await _context.SaveChangesAsync();
EventHasMusicGenre music1 = new EventHasMusicGenre()
{
EventId = newEvent.EventId,
MusicGenreId = eventFromClient.MusicGenres[0].MusicGenreId
};
EventHasMusicGenre music2 = new EventHasMusicGenre()
{
EventId = newEvent.EventId,
MusicGenreId = eventFromClient.MusicGenres[1].MusicGenreId
};
await _eventHasMusicGenresRepository.PostEventHasMusicGenre(music1);
await _eventHasMusicGenresRepository.PostEventHasMusicGenre(music2);
await _context.SaveChangesAsync();
I have to create an event object who has a many to many relationship so the linking table will be eventHasMusicGenre who has it s own repo and methods is this best way to do it?
this pattern is fine, however see below for alternative:
List<EventHasMusicGenre> genres = new List<EventHasMusicGenre>();//declare list
foreach(var g in eventFromClient.MusicGenres)//loop client array
{
genres.Add(new EventHasMusicGenre(){//add to list
MusicGenreId = g.MusicGenreId
})
}
var newEvent = new Event
{
Name = eventFromClient.Name,
StartDate = eventFromClient.StartDate,
EndDate = eventFromClient.EndDate,
StartTime = eventFromClient.StartTime,
EndTime = eventFromClient.StartTime,
Description = eventFromClient.Description,
DressCodeId = eventFromClient.DressCodeId,
PolicyMinimumAge = eventFromClient.PolicyMinimumAge,
PolicyDescription = eventFromClient.PolicyDescription,
MusicGenres : [ genres ] //list as part of model, no need to worry about the id
};
This way you dont have to hardcode indices
I have two sets of codes. The first one doesn't give me the list of data but the second on does. Please see codes below:
First Code:
Model
public class Student
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
DataConnection
public class DataConnection : DbContext
{
public DataConnection()
: base("DefaultConnection")
{
}
public DbSet<Student> Students { get; set; }
}
Interface
public interface IStudent
{
List<Student> StudentList();
void InsertStudent(Student student);
void UpdateStudent(Student student);
Student GetStudentById(int id);
void DeleteStudent(int id);
}
Concrete
readonly DataConnection _context;
public StudentConcrete()
{
_context = new DataConnection();
}
public List<Student> StudentList()
{
var studentList = (from s in _context.Students select s).ToList();
return studentList;
}
Second Code
Concrete
readonly DataConnection _context;
public StudentConcrete()
{
_context = new DataConnection();
}
public List<Student> StudentList()
{
SqlConnection xxx = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
var cmd = new SqlCommand("GetAllStudents", xxx);
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
return (from DataRow row in ds.Tables[0].Rows
select new Student()
{
Age = Convert.ToInt32(row["Age"]),
FirstName = row["FirstName"].ToString(),
Gender = row["Gender"].ToString(),
LastName = row["LastName"].ToString()
}).ToList();
}
else
{
return null;
}
}
I would like to get the data using the first code but I don't know where I get it wrong. My SP is just to get the students.
I suspected that maybe you are retrieving the records from another table somehow. Would you try to add Table attribute for Student entity.
using System.ComponentModel.DataAnnotations.Schema;
[Table("Students")]
public class Student
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
Am Trying to Print out a student Identity Card using crystal report but all what i could get was this error popping up The data source object is invalid.
Guys please help me to check on this code if am making any mistake...
this is the model
public class CardModel
{
// Properties
public string Department { get; set; }
public string ExpiryDate { get; set; }
public string FirstName { get; set; }
public Sex Gender { get; set; }
public Guid Id { get; set; }
public string MiddleName { get; set; }
public string RegistrationNo { get; set; }
public byte[] SecuritySign { get; set; }
public byte[] StudentPhoto { get; set; }
public string Surname { get; set; }
}
public static class CardModelExtention
{
public static CardModel ToCardModel(this Student identity)
{
return new CardModel
{
Id = identity.Id,
FirstName = identity.FirstName,
MiddleName = identity.MiddleName,
Surname = identity.Surname,
StudentPhoto = identity.Photo.RawPhoto,
SecuritySign = identity.SecuritySignature.RawSignature,
Gender = identity.Sex,
ExpiryDate = identity.ExpiryDate,
Department = identity.Department.DepartmentName,
RegistrationNo = identity.RegistrationNo
};
}
}
and here is the service am using to pull the information from database
public class StudentService : IStudentService
{
ERMUoW _ow;
public StudentService()
{
_ow = new ERMUoW();
}
public CardModel GetStudentById(Guid id)
{
CardModel obj3 = new CardModel();
Student student = _ow.Students.GetAllIncluding(new Expression<Func<Student, object>>[] { st => st.Photo, st => st.Signature, st => st.SecuritySignature, st => st.Department }).Where(x => x.Id == id).SingleOrDefault();
var cardInfo = student.ToCardModel();
return cardInfo;
}
}
public interface IStudentService
{
CardModel GetStudentById(Guid id);
}
This is it and everything around here is working fine and am getting the data very well but when I send it to the method in my contrller that generate the identity card I get that error message
this is the code that generate the card using crytal report
public ActionResult PrintCard(Guid id)
{
var student = _studentCardService.GetStudentById(id);
ReportDocument read = new ReportDocument();
read.Load(Server.MapPath("~/Reports/rpt_StudentCard.rpt"));
read.SetDataSource(student);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
try
{
Stream stream = read.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "StudentIdentityCard.pdf");
}
catch (Exception ex)
{
throw ex;
}
}
I will really Appreciate your help thank you...
The data source have to be a List of elements... not a single element.