I have a .xlsx file, which contains the first column projectname, second column description.
I want to create a console app for create projects from azureProjects.xlsx file using Azure DevOps Rest API. I already implement the code below, but I can't understand how to read from .xlsx file and implement the code. Can you have a solution to help me?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace WorkItemTest
{
class AzureAdmin
{
private readonly Uri uri;
private readonly string personalAccessToken;
public AzureAdmin(string orgName, string personalAccessToken)
{
this.uri = new Uri("https://dev.azure.com/" + orgName);
this.personalAccessToken = personalAccessToken;
}
public async Task<bool> createProject()
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
Encoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalAccessToken))));
var req = new Root
{
name = "test3",
description = "test about smthng",
visibility = 0,
capabilities = new Capabilities
{
versioncontrol = new Versioncontrol {sourceControlType = "Git"},
processTemplate = new ProcessTemplate
{
templateTypeId = "b8a3a935-7e91-48b8-a94c-606d37c3e9f2"
}
}
};
var result = await client.PostAsJsonAsync($"{uri}/_apis/projects?api-version=5.1", req); //
Console.WriteLine(result.StatusCode);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return true;
}
public class Versioncontrol
{
public string sourceControlType { get; set; }
}
public class ProcessTemplate
{
public string templateTypeId { get; set; }
}
public class Capabilities
{
public Versioncontrol versioncontrol { get; set; }
public ProcessTemplate processTemplate { get; set; }
}
public class Root
{
public string name { get; set; }
public string description { get; set; }
public int visibility { get; set; }
public Capabilities capabilities { get; set; }
}
}
}
You have implemented how to create a team project in DevOps, what you need is reading the project names from .xlsx file. This is not implemented via Azure Devops API, you just need to get help from Excel side to get how to read data from .xlsx file via api.
Check the following link to see whether it helps you:
https://learn.microsoft.com/en-us/troubleshoot/dotnet/csharp/query-excel-data-aspx-page
Related
dotNet Core 5 C# Web API project, Service class adds objects (based on a viewmodel) to a list. Debugging shows all data correct as the object is built and added to the List, but the returned result has multiple (matching the count it should have) copies of the last item added only. Service code and viewmodel code below. What am I missing?
using FS.Data.Repositories;
using FS.Models;
using FS.ViewModels;
using FS.ViewModels.APVendor;
using Microsoft.Extensions.Options;
using NLog;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace FS.Services
{
public class GLAccountSetService : IGLAccountSetService
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
private readonly IOptions<AppSettingsModel> AppSettings;
private readonly HttpClient Client;
GlAccountSetResponseViewModel result = new GlAccountSetResponseViewModel();
public GLAccountSetService(HttpClient client, IOptions<AppSettingsModel> app)
{
Client = client; //?? throw new ArgumentNullException(nameof(client));
AppSettings = app;
}
public async Task<GlAccountSetResponseViewModel> GetGLAccountSets(IList<GlAccountSetRequestViewModel> req, IAPCorpRepository apcr)
{
result.GlAccountSetViewModels = new List<GlAccountSetViewModel>();
result.SuccessErrorWarningResult = new SuccessErrorWarningResult();
GlAccountSetViewModel accountSet = new GlAccountSetViewModel();
string payorID = "";
string payeeID = "";
string payorCashAccount = "";
string payeeCashAccount = "";
string expenseAccount = "";
string offsetAccount = "";
string type = "";
long reqID = 0;
foreach (GlAccountSetRequestViewModel glr in req)
{
type = glr.Type;
expenseMain = glr.ExpenseAccount;
payorID = glr.PayorCorpID;
payeeID = glr.PayeeCorpID;
reqID = glr.ReqID;
//...skipping calculation code that works
accountSet.ExpenseAccount = expenseAccount;
accountSet.PayorCashAccount = payorCashAccount;
accountSet.PayeeCashAccount = payeeCashAccount;
accountSet.OffsetAccount = offsetAccount;
accountSet.ReqID = reqID;
result.GlAccountSetViewModels.Add(accountSet);
}
return result;
}
}
}
using FS.Common;
using System.Collections.Generic;
namespace FS.ViewModels.APVendor
{
public class GlAccountSetResponseViewModel : FSObject<GlAccountSetResponseViewModel>
{
public IList<GlAccountSetViewModel> GlAccountSetViewModels { get; set; }
public SuccessErrorWarningResult SuccessErrorWarningResult { get; set; }
}
}
namespace FS.ViewModels.APVendor
{
public class GlAccountSetViewModel
{
public string ExpenseAccount { get; set; }
public string PayorCashAccount { get; set; }
public string PayeeCashAccount { get; set; }
public string OffsetAccount { get; set; }
public long ReqID { get; set; }
}
}
You're adding the same accountSet instance to the list multiple times, only modifying it in the loop. Thus all references to it in the list will "have" the most recently set values.
You need to create a new GlAccountSetViewModel instance in the loop and add that one, or make it a struct to copy it when being added.
Using an open API (I'm using New York Times book API) create an API Gateway endpoint that does the following:
Retrieves data from an API. Stores the data in a database.
I'm able to retrieve the data and store it in a string but I'm having difficulties extracting that data from the string and storing it into a dynamo DB. Any help is appreciated thank you.
Here is my code:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Amazon.Lambda.Core;
using Newtonsoft.Json.Linq;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.DynamoDBv2.Model;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace last
{
public class Result
{
public string url { get; set; }
public string publication_dt { get; set; }
public string byline { get; set; }
public string book_title { get; set; }
public string book_author { get; set; }
public string summary { get; set; }
public List<string> isbn13 { get; set; }
}
public class Root
{
public string status { get; set; }
public string copyright { get; set; }
public int num_results { get; set; }
public List<Result> results { get; set; }
}
public class Function
{
private static AmazonDynamoDBClient client1 = new AmazonDynamoDBClient();
public static readonly HttpClient client = new HttpClient();
public async Task<ExpandoObject> FunctionHandler(string input, ILambdaContext context)
{
string tblName = "last";
string url = "https://api.nytimes.com/svc/books/v3/reviews.json?title=Becoming&api-key=myKey";
string message = await client.GetStringAsync(url);
Result myDeserializedClass = JsonConvert.DeserializeObject<Result>(message);
var request = new PutItemRequest
{
TableName = tblName,
Item = new Dictionary<string, AttributeValue>()
{
{ "bookId", new AttributeValue { S = "202" }},
{ "publication_dt", new AttributeValue { S = myDeserializedClass.publication_dt.ToString() }},
{ "byline", new AttributeValue { S = myDeserializedClass.byline.ToString() }},
{ "book_title", new AttributeValue { S = myDeserializedClass.book_title.ToString()}},
{ "book_author", new AttributeValue { S = myDeserializedClass.book_author.ToString() }},
{ "summary", new AttributeValue { S = myDeserializedClass.summary.ToString() }},
{ "isbn13", new AttributeValue { S = myDeserializedClass.isbn13.ToString()}},
}
};
await client1.PutItemAsync(request);
//Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(message);
//await tblName.PutItemAsync((Document)myDeserializedClass.ToString());
return JsonConvert.DeserializeObject<ExpandoObject>(message);
}
}
}
First time working with JSON and trying to figure this one out. I am able to connect to the API and get the JSON string to display in my textbox. I am confused on how to properly display the data correctly in the textbox.
This my code I have.
{
GetReportList p = new GetReportList();
var client = new RestClient(p.WebReportList);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "Value");
var thisJsonStr = "{\"Credentials\": { \"ApiKey\": \"xxxxxxxx\",\"MerchantID\": \"xxxxxxx\",\"StoreID\":\"xxxxx\",\"Username\": \"xxxxx\",\"Password\": \"xxxx\"},\"ReportID\": [\"34\"]}";
request.AddParameter("application/json", thisJsonStr, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
deseiralizeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Report>(response.Content);
ReportListbx.Text = (response.Content);
}
My output looks like this when I debug it.
{"Result":"OK","Reports":[{"ReportID":"18","Name":"END OF DAY","Type":"group"},{"ReportID":"34","Name":"MANDY REPORT","Type":"group"},{"ReportID":"17","Name":"Lottery Paid Out","Type":"preset"}
My output i want it to be the "ReportID","name", Type"
Thanks
#Saeed Aghdam
I have edited the code to this
request.AddParameter("application/json", thisJsonStr, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var json = response.Content;
var deseiralizeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Report>(json);
foreach (var report in deseiralizeObject.Reports)
ReportListbx.Text = ($"{report.ReportID} - {report.Name} - {report.Type}");
And I get the last record from the JSON data.
I write a very simple console application, in this app, it gets your provided sample JSON and deserializes it to a class. so you can iterate items (elements) and display them.
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
public class Report
{
public string Result { get; set; }
public IEnumerable<ReportItem> Reports { get; set; }
}
public class ReportItem
{
public string ReportID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
class Program
{
static void Main(string[] args)
{
var json = #"{""Result"":""OK"",""Reports"":[{""ReportID"":""18"",""Name"":""END OF DAY"",""Type"":""group""},{""ReportID"":""34"",""Name"":""MANDY REPORT"",""Type"":""group""},{""ReportID"":""17"",""Name"":""Lottery Paid Out"",""Type"":""preset""}]}";
var deseiralizeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Report>(json);
foreach(var report in deseiralizeObject.Reports)
Console.WriteLine($"{report.ReportID} - {report.Name} - {report.Type}");
Console.ReadKey();
}
}
}
Edit: An alternative for the above method is using a dynamic object, the following code do the same as the above codes are doing:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
public class Report
{
public string Result { get; set; }
public IEnumerable<ReportItem> Reports { get; set; }
}
public class ReportItem
{
public string ReportID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
class Program
{
static void Main(string[] args)
{
var json = #"{""Result"":""OK"",""Reports"":[{""ReportID"":""18"",""Name"":""END OF DAY"",""Type"":""group""},{""ReportID"":""34"",""Name"":""MANDY REPORT"",""Type"":""group""},{""ReportID"":""17"",""Name"":""Lottery Paid Out"",""Type"":""preset""}]}";
dynamic d = JObject.Parse(json);
foreach (var report in d.Reports)
Console.WriteLine($"{report.ReportID} - {report.Name} - {report.Type}");
Console.ReadKey();
}
}
}
Screenshot:
I'm using C# and UWP xml to create a news feed. Like a phone news widget but for the computer. I came across https://newsapi.org/ and thought it was interesting. But I don't know how to implement and there isn't any tutorials on C# for this api website. How do I use this and how do I show the article.Title, article.Author, and article.Description on 3 textblocks I created?
edit: I found a video for c# but it is for console.writeline, not a xaml front page.
So what I did was create a new class.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NewsAPI;
using NewsAPI.Models;
using NewsAPI.Constants;
using System.Net.Http;
using Newtonsoft.Json;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
namespace news
{
public class newsapi
{
HttpClient client = new HttpClient();
//public static async void Main(string[] args)
//{
// newsapi program = new newsapi();
// await program.GetArticles();
//}
//public async Task GetArticles()
//{
// string response = await client.GetStringAsync("https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=06112b69bb054cfeb70bbf188873f98e");
// NewsResponse newsObject = JsonConvert.DeserializeObject<NewsResponse>(response);
//}
public async static Task<Article> GetArticlesMain()
{
var http = new HttpClient();
var response = await http.GetAsync("https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=06112b69bb054cfeb70bbf188873f98e");
var result = await response.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(Article));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (Article)serializer.ReadObject(ms);
return data;
}
[DataContract]
public class NewsResponse
{
[DataMember]
public string status { get; set; }
[DataMember]
public int totalResults { get; set; }
[DataMember]
public List<Article> Articles { get; set; }
}
[DataContract]
public class Article
{
[DataMember]
public string Title { get; set; }
}
}
}
and tried to get the title of the news api in my mainpage.xaml in a textblock in a page_loaded event:
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
//RootObject myWeather = await OpenWeather.GetWeather(20, 30);
Article article = await newsapi.GetArticlesMain();
tbContent.Text = article.Title;
}
But the textblock doesn't show anything and an exception user-unhandled was thrown in "tbContent.Text = article.Title" this line saying "Value cannot be null". So what is going on and how to fix it?
When you get the Json string from the network, if you want to convert to a type, you need to provide a class corresponding to the json structure.
var serializer = new DataContractJsonSerializer(typeof(Article));
Here is the main problem, the obtained json string should be of type NewsResponse, so it should be like this:
var serializer = new DataContractJsonSerializer(typeof(Article));
This is a complete process:
News.cs
public class NewsApi
{
public async static Task<List<Article>> GetArticlesMain()
{
var http = new HttpClient();
var response = await http.GetAsync("your_news_url");
var result = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<NewsResponse>(result);
return data.articles;
}
}
public class NewsResponse
{
public string status { get; set; }
public int totalResults { get; set; }
public List<Article> articles { get; set; }
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
public string content { get; set; }
}
public class Source
{
public string id { get; set; }
public string name { get; set; }
}
News.xaml.cs
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
List<Article> articles = await NewsApi.GetArticlesMain();
tbContent.Text = articles.First().title;
}
I have a console application which needs to connect to SQL Reporting Services on SQL Server Express 2012.
All the exporting logic should be implemented in a separate dll, and the paths should be dynamic (I have loop through various settings for various servers/reports and export them to Excel one by one).
I tried to follow these tutorials:
http://www.aspose.com/docs/display/wordsreportingservices/Rendering+Reports+Programmatically
http://blogs.msdn.com/b/selvar/archive/2010/12/13/accessing-the-reportexecutionservice-render-method-when-reporting-service-2008-r2-is-in-forms-based-authentication.aspx
Basically, I added web references:
http://localhost:80/ReportServer_SQLEXPRESS12/ReportExecution2005.asmx
and
http://localhost:80/ReportServer_SQLEXPRESS12/ReportService2010.asmx
to my dll. Looks good so far, except those nasty app.config settings (I'll have to adjust them dynamically later).
Then I tried to do as in the example:
// Create Web service proxies.
ReportingService2010.ReportingService2010 rs = new ReportingService2010.ReportingService2010();
ReportExecutionService.ReportExecutionService rsExec = new ReportExecutionService.ReportExecutionService();
and got some troubles:
Error 76 The type or namespace name 'ReportExecutionService' does not exist in the namespace 'MyDllNamespace.ReportExecutionService' (are you missing an assembly reference?)
Error 74 The type or namespace name 'ReportingService2010' does not exist in the namespace 'MyDllNamespace.ReportingService2010' (are you missing an assembly reference?)
Now where do I go next, how do I use the Reporting Services API, if I cannot even create a proxy object? Or should I better use ServerReport class form the Winforms ReportViewer instead of these web references?
Even one of Microsoft examples is using ReportViewer in a console application, but it seems a bit awkward to import Winforms in a console app.
I hope the following will help (extract of pertinent parts of code)
using (ZUtilities.SSRS.Report report = new ZUtilities.SSRS.Report {
ReportServerPath = VParameter.GetValue("SSRS_WebServiceUrl", _repo.Parameters).ToString(),
Format = rformat,
ReportPath = "some_path_on_ssrs_server"
}) {
report.Params.Add("Id", id.ToString());
report.Credentials = nwc;
MemoryStream ms = new MemoryStream();
report.Render().CopyTo(ms);
FileContentResult fsr = new FileContentResult(ms.ToArray(), rctype);
fsr.FileDownloadName = String.Format("EPV-{0}-{1:yyyyMMdd}.{2}", epv.ExternalReference, DateTime.Now, fext);
ms.Close();
return fsr;
}
with the following (be carefull to the stream management)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace ZUtilities.SSRS {
public enum ReportFormats {
Html = 1,
MHtml,
Pdf,
Xlsx,
Docx
}
public class ReportFormat {
static ReportFormat() {
Html = new ReportFormat { Code = ReportFormats.Html, Instruction = "HTML4.0" };
MHtml = new ReportFormat { Code = ReportFormats.MHtml, Instruction = "MHTML" };
Pdf = new ReportFormat { Code = ReportFormats.Pdf, Instruction = "PDF" };
Xlsx = new ReportFormat { Code = ReportFormats.Xlsx, Instruction = "EXCELOPENXML" };
Docx = new ReportFormat { Code = ReportFormats.Docx, Instruction = "WORDOPENXML" };
}
private ReportFormat() {
}
public ReportFormats Code { get; set; }
public String Instruction { get; set; }
public static ReportFormat Html { get; private set; }
public static ReportFormat MHtml { get; private set; }
public static ReportFormat Pdf { get; private set; }
public static ReportFormat Xlsx { get; private set; }
public static ReportFormat Docx { get; private set; }
public static ReportFormat ByCode(ReportFormats code) {
switch (code) {
case ReportFormats.Html: return Html;
case ReportFormats.MHtml: return Html; //<<======================
case ReportFormats.Pdf: return Pdf;
case ReportFormats.Xlsx: return Xlsx;
case ReportFormats.Docx: return Docx;
default : return null;
}
}
}
public class Report : IDisposable {
private HttpWebRequest _httpWReq;
private WebResponse _httpWResp;
public Report() {
_httpWReq = null;
_httpWResp = null;
Format = ReportFormats.Html;
Params = new Dictionary<String, String>();
}
public Dictionary<String, String> Params { get; set; }
public String ReportServerPath { get; set; }
public String ReportPath { get; set; }
public ReportFormats Format { get; set; }
public NetworkCredential Credentials { get; set; }
//public String PostData { get { return String.Format("rs:Command=Render&rs:Format={0}", ReportFormat.ByCode(Format).Instruction); } }
public String PostData { get {
StringBuilder sb = new StringBuilder(1024);
sb.AppendFormat("rs:Command=Render&rs:Format={0}", ReportFormat.ByCode(Format).Instruction);
if (Format == ReportFormats.Html) {
sb.Append("&rc:Toolbar=false");
}
foreach (var kv in Params) {
sb.AppendFormat("&{0}={1}", kv.Key, kv.Value);
}
return sb.ToString();
} }
public String ReportFullPath { get { return ReportServerPath + "?/" + ReportPath; } }
public Stream Render() {
_httpWReq = (HttpWebRequest)HttpWebRequest.Create(ReportFullPath);
_httpWReq.Method = "POST";
if (Credentials != null)
_httpWReq.Credentials = Credentials;
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
_httpWReq.ContentType = "application/x-www-form-urlencoded";
_httpWReq.ContentLength = byteArray.Length;
Stream dataStream = _httpWReq.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
if (_httpWResp != null )
_httpWResp.Close();
_httpWResp = _httpWReq.GetResponse();
return _httpWResp.GetResponseStream();
}
public void RenderTo(String fileName) {
Stream receiveStream = Render();
Stream ds = File.Open(fileName, FileMode.Create);
receiveStream.CopyTo(ds);
ds.Close();
receiveStream.Close();
}
public void Dispose() {
if (_httpWResp != null) {
_httpWResp.Close();
_httpWResp = null;
}
if (_httpWReq != null) {
_httpWReq = null;
}
}
}
}