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:
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've created a bot with Microsoft bot framework for Messenger.
All work great. i can recieve and send message to messanger but in messanger mobile push notification not work. I omit the property notification_type because facebook guide say
notification_type is optional; by default, messages will be REGULAR
push notification type
It is a Framework bug?
My code:
ConnectorClient connector = new ConnectorClient(new Uri(servUri), microsoftAppId: appId, microsoftAppPassword: pass);
ResourceResponse conversationId = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);
IMessageActivity activity = Activity.CreateMessageActivity();
activity.Id = conversationId.Id;
activity.Type = ActivityTypes.Message;
activity.From = botAccount;
activity.Conversation = conversation;
activity.Recipient = userAccount;
activity.Text = "hello";
await connector.Conversations.SendToConversationAsync((Activity)activity);
I've used activity.ChannelData and all work good
I post my solution, can be useful to someone
Add the attachment to the activity:
activity.ChannelData = new FacebookChannelData()
{
Attachment = GetFacebookAttachment()
};
create the attachment:
private static FacebookAttachment GetFacebookAttachment()
{
return new FacebookAttachment()
{
Payload = new GenericTemplate
{
Elements = new[] {
new TemplateElements(){
Title = "my title",
ItemUrl = "https://example.com",
ImageUrl = "https://example.com/test.jpg",
Subtitle = "subtitle",
Buttons = new[] {
new TemplateButtons() {
Type = "web_url",
Url = "https://example.com",
Title = "button title"
}
}
}
}
}
};
}
and then the classes:
public class FacebookChannelData
{
public FacebookChannelData() {
this.NotificationType = "REGULAR";
}
[JsonProperty("notification_type")]
public string NotificationType { get; set; }
[JsonProperty("attachment")]
public FacebookAttachment Attachment { get; internal set; }
}
public class FacebookAttachment
{
public FacebookAttachment()
{
this.Type = "template";
}
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("payload")]
public dynamic Payload { get; set; }
public override string ToString()
{
return this.Payload.ToString();
}
}
public class GenericTemplate
{
public GenericTemplate()
{
this.TemplateType = "generic";
}
[JsonProperty("template_type")]
public string TemplateType { get; set; }
[JsonProperty("elements")]
public TemplateElements[] Elements { get; set; }
}
public class TemplateElements
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("item_url")]
public string ItemUrl { get; set; }
[JsonProperty("image_url")]
public string ImageUrl { get; set; }
[JsonProperty("subtitle")]
public string Subtitle { get; set; }
[JsonProperty("buttons")]
public TemplateButtons[] Buttons { get; set; }
}
public class TemplateButtons
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("payload")]
public string Payload { get; set; }
}
notification_type IS optional - but only in the context of when you're actually specifying a ChannelData on your activity.
So just add (given that you're using Newtonsoft.Json.Linq;)
activity.ChannelData = JObject.FromObject(new
{
notification_type = "REGULAR"
});
and you'll get your notification, provided that your client app has not disabled notifications.
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.
I'm developing WP8 app and i'm new to it.. i want to know my post method is correct or not because i'm unable to post my data in the url it produces an exception..
My Class Contents...
public class Register
{
public int id { get; set; }
public string password_reset_hash { get; set; }
public string temp_password { get; set; }
public bool remember_me { get; set; }
public string activation_hash { get; set; }
public string ip_address { get; set; }
public bool status { get; set; }
public bool activated { get; set; }
public string permissions { get; set; }
public DateTime last_login { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public string email { get; set; }
public string password { get; set; }
public string conformpassword { get; set; }
public string username { get; set; }
}
here is my code..
public void btn_register_click(object sender, RoutedEventArgs e)
{
string url="myurl";
Register res=new Register();// my class
res.email = txt_email.Text;
res.password = txt_password.Text;
res.conformpassword = txt_conf_psswrd.Text;
res.username = txt_username.Text;
res.created_at = DateTime.Now;
res.last_login = DateTime.Now;
res.updated_at = DateTime.Now;
res.status = true;
json = JsonConvert.SerializeObject(res);
WebClient wc = new WebClient();
var URI = new Uri(url);
wc.Headers["Content-Type"] = "application/json";
wc.Headers["ACCEPT"] = "application/json";
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.UploadStringAsync(URI, "POST", json);
}
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
MessageBox.Show(e.Result);
//e.result fetches you the response against your POST request.
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString()); //i'm getting error here..
}
}
My Screen Design..
Error is..
Thanks
It looks to me like there is a problem with the URI you are using. The error message you posted shows the server returning a "Not found" header. Maybe it just is not quite correct? I did not see the exact URI in the code you posted. string url="myurl"; does not look like this is the url you want to use.
That's also why you can't access the response stream without an exception with this line: MessageBox.Show(e.Result);. There just is no valid response. This is documented here: http://msdn.microsoft.com/de-de/library/system.net.uploadstringcompletedeventargs.result%28v=vs.110%29.aspx.
You can determine if such an error occurred by checking the Error property of UploadStringCompletedEventArgs (http://msdn.microsoft.com/de-de/library/system.net.uploadstringcompletedeventargs%28v=vs.110%29.aspx).
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