I am trying to upload file in blackblaze using Asp.Net Web Api but I am fount error : cannot convert from 'System.IO.Stream' to 'string' blackblaze. My method is Right or wrong
I am write code in visual studio 2022
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Text;
namespace blackblaze.Controllers
{
public class BlackBlazeController : Controller
{
public async Task<IActionResult> BlackBlazeFileUpload([FromBody] BlackBlaze blackBlaze)
{
try
{
String startLargeFileJsonStr = "{\"bucketId\":\"" + blackBlaze.BucketId + "\",\"fileName\":\"" + blackBlaze.FileName + "\",\"contentType\":\"" + blackBlaze.ContentType + "\"}";
byte[] jsonData = Encoding.UTF8.GetBytes(startLargeFileJsonStr);
HttpWebRequest startLargeFileRequest = (HttpWebRequest)WebRequest.Create(blackBlaze.ApiUrl + "/b2api/v2/b2_start_large_file");
using (Stream stream = startLargeFileRequest.GetRequestStream())
{
stream.Write(jsonData, 0, jsonData.Length);
stream.Close();
}
HttpWebResponse startLargeFileResponse = (HttpWebResponse)startLargeFileRequest.GetResponse();
using (StringReader responseReader = new(startLargeFileResponse.GetResponseStream()))
{
String json = responseReader.ReadToEnd();
}
startLargeFileResponse.Close();
return Ok();
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
}
}```
My class
```namespace blackblaze.Model
{
public class BlackBlaze
{
public string? BucketId { get; set; }
public IFormFile? FileName { get; set; }
public string? ContentType { get; set; }
public string? ApiUrl { get; set; }
//public string? authorizationToken { get; set; }
}
}
Related
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
I want to get all variables from https://api.coinmarketcap.com/v1/ticker/ in my c# console application.
How can I do this?
I started with getting the whole page as a stream. What to do now?
private static void start_get()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create
(string.Format("https://api.coinmarketcap.com/v1/ticker/"));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
Console.WriteLine(_Answer.ReadToEnd());
}
First you need a custom class to use for deserialization:
public class Item
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
[JsonProperty(PropertyName = "24h_volume_usd")] //since in c# variable names cannot begin with a number, you will need to use an alternate name to deserialize
public string volume_usd_24h { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}
Next, you can use Newtonsoft Json, a free JSON serialization and deserialization framework in the following way to get your items (include the following using statements):
using System.Net;
using System.IO;
using Newtonsoft.Json;
private static void start_get()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("https://api.coinmarketcap.com/v1/ticker/"));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
string jsonString;
using (Stream stream = WebResp.GetResponseStream()) //modified from your code since the using statement disposes the stream automatically when done
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(jsonString);
Console.WriteLine(items.Count); //returns 921, the number of items on that page
}
Finally, the list of elements is stored in items.
A simplified version of Keyur PATEL's work.
static void GetCoinValues()
{
string json = new WebClient().DownloadString("https://api.coinmarketcap.com/v1/ticker/");
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
foreach (var item in items)
{
Console.WriteLine("ID: " + item.id.ToUpper());
Console.WriteLine("Name: " + item.name.ToUpper());
Console.WriteLine("Symbol: " + item.symbol.ToUpper());
Console.WriteLine("Rank: " + item.rank.ToUpper());
Console.WriteLine("Price (USD): " + item.price_usd.ToUpper());
Console.WriteLine("\n");
}
}
I am trying to post a request to the server with JSON data in "form-data" using HttpWebrequest in C#.
I tried my best but didn't get any successful results. I tried even with WebClient but not successful.
please find the code below which I have tried.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.IO;
using Newtonsoft.Json;
using System.Web;
namespace Console_Workstation
{
class UpdatingSrialnumbersvia_API
{
#region Properties
public class JsonContent
{
public DateTime date { get; set; }
public string reason { get; set; }
public string description { get; set; }
public string reference_number { get; set; }
public string adjustment_type { get; set; }
public List<line_items> line_item { get; set; }
}
public class line_items
{
public long item_id { get; set; }
public string name { get; set; }
public int quantity_adjusted { get; set; }
public List<string> serial_numbers { get; set; }
public int item_total { get; set; }
public string unit { get; set; }
public bool is_combo_product { get; set; }
public string adjustment_account_name { get; set; }
public long warehouse_id { get; set; }
public string warehouse_name { get; set; }
}
#endregion
public static void Main()
{
#region JSon Content
line_items items = new line_items
{
item_id = 519558000000686015,
name = "Acer 19.5-inch LED Monitor (K202HQL-AB)",
quantity_adjusted = 1,
serial_numbers = new List<string>()
{
"TPS5678AMZ"
},
item_total = 15,
unit = "qty",
is_combo_product = false,
adjustment_account_name = "Cost of Goods Sold",
warehouse_id = 519558000000076101,
warehouse_name = "QSAI"
};
JsonContent content = new JsonContent
{
date = new DateTime(2019 - 09 - 12),
reason = "Extra Stock",
description = "",
reference_number = "Test-IA-456",
adjustment_type = "quantity",
line_item = new List<line_items>() { items }
};
#endregion
try
{
string json = JsonConvert.SerializeObject(content, Formatting.Indented);
string strResponse = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(#"https://inventory.zoho.com/api/v1/inventoryadjustments?organization_id=123456789");
request.Method = "POST";
request.Headers.Add("Authorization", "*******************************");
request.ContentType = "multipart/form-data";
request.Host = "inventory.zoho.com";
request.Headers.Add("name", "JsonString=" + json);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("Error code in response recieved: " + response.StatusCode.ToString());
}
using (Stream stream = response.GetResponseStream())
{
if (stream != null)
{
using (StreamReader streamReader = new StreamReader(stream))
{
strResponse = streamReader.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadKey();
}
}
}
}
The JSON format will be like this
{
"date": "2019-09-11",
"reason": "Extra Stock",
"description": "",
"reference_number": "Test-IA-123",
"adjustment_type": "quantity",
"line_items": [
{
"item_id": 519558000000686015,
"name": "Acer 19.5-inch LED Monitor (K202HQL-AB)",
"quantity_adjusted": 1,
"serial_numbers":[
"TPS1234AMZ"
],
"item_total": 15,
"unit": "qty",
"is_combo_product": false,
"adjustment_account_name": "Cost of Goods Sold",
"warehouse_id": 519558000000076101,
"warehouse_name": "QSAI"
}
]
}
PFA for the image from PostMan
I have a WPF application that calls an API and creates an System.Xml.Linq.XDocument using XDocument.Parse(string). I am running into a problem where an XmlException ("Root element is missing") is thrown when I try to do this, but my XML is completely valid. I tried syntax-checking it by calling the API in my browser and checking its syntax, calling the API in my application and Console.WriteLineing the response, and using various XML syntax validators (all of which returned no errors).
A sample XML response from the API is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<event title="Event 1" id="75823347" icon="www.example.com/images/event1-icon.png" uri="www.example.com/rsvp/event1" mode="none" price="10.00" cover="www.example.com/event1-cover.png" enddate="2016-06-01 14:00:00" startdate="2016-06-01 12:00:00" address="1 Example St, Example City State 12345" location="Example Place" description="This is an event" shortdescription="This is an event" theme="auto" color="#FF000000"/>
</response>
This is my application's code:
public static WebRequest CreateRequest(string baseUrl, string httpMethod, Dictionary<string, string> requestValues) {
var requestItems = requestValues == null ? null : requestValues.Select(pair => string.Format("&{0}={1}", pair.Key, pair.Value));
var requestString = "";
if (requestItems != null)
foreach (var s in requestItems)
requestString += s;
var request = WebRequest.CreateHttp(baseUrl + CredentialRequestString + requestString);
request.Method = httpMethod.ToUpper();
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
return request;
}
public static WebRequest CreateRequest(string apiEndpoint, string endpointParam, int apiVersion, string httpMethod, Dictionary<string, string> requestValues) {
return CreateRequest(string.Format("http://www.example.com/api/v{0}/{1}/{2}", apiVersion, apiEndpoint, endpointParam), httpMethod, requestValues);
}
public static async Task<string> GetResponseFromServer(WebRequest request) {
string s;
using (var response = await request.GetResponseAsync()) {
using (var responseStream = response.GetResponseStream()) {
using (var streamReader = new StreamReader(responseStream)) {
s = streamReader.ReadToEnd();
}
}
}
return s;
}
public static async Task<List<Event>> GetEvents() {
var response = await GetResponseFromServer(CreateRequest("events", "", 1, "GET", null));
Console.WriteLine(response); //validation
var data = XDocument.Parse(response).Root; //XmlException: Root element is mising
return new List<Event>(data.Elements("event").Select(e => Event.FromXml(e.Value)));
}
Why is this happening?
The following code works
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
var data = XDocument.Load(FILENAME);
Event _event = Event.FromXml(data.Descendants("event").FirstOrDefault());
}
}
public class Event
{
public string title { get ; set; }
public string icon {get; set; }
public string uri { get; set; }
public string mode { get;set; }
public decimal price { get; set; }
public string cover { get; set; }
public DateTime enddate { get; set; }
public DateTime startdate { get; set; }
public string address { get; set; }
public string location { get; set; }
public string description { get; set; }
public string shortdescription { get; set; }
public string theme { get; set; }
public uint color { get; set; }
public static Event FromXml(XElement data)
{
Event _event = new Event();
_event.title = (string)data.Attribute("title");
_event.icon = (string)data.Attribute("icon");
_event.uri = (string)data.Attribute("uri");
_event.mode = (string)data.Attribute("mode");
_event.price = (decimal)data.Attribute("price");
_event.cover = (string)data.Attribute("cover");
_event.enddate = (DateTime)data.Attribute("enddate");
_event.startdate = (DateTime)data.Attribute("startdate");
_event.address = (string)data.Attribute("address");
_event.location = (string)data.Attribute("location");
_event.description = (string)data.Attribute("description");
_event.shortdescription = (string)data.Attribute("shortdescription");
_event.theme = (string)data.Attribute("theme");
_event.color = uint.Parse(data.Attribute("color").Value.Substring(1), System.Globalization.NumberStyles.HexNumber) ;
return _event;
}
}
}
I used HttpWebRequest to get the content from a website.
The problem is that I got a response in json and I don't really know how to use, convert and implement that data in my program.
Current code:
namespace Web_Scraper
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string final_response = stream.ReadToEnd();
Console.WriteLine("Genuine Purity Fist");
Console.WriteLine(final_response);
Console.ReadKey();
}
}
}
Response:
{"success":true,"lowest_price":"1,05\u20ac","volume":"26","median_price":"1,06\u20ac"}
json2csharp code:
public class RootObject
{
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
Hey you could downloade Json.NET and parse your json string like this:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
var final_response = stream.ReadToEnd();
// Converts the unicode to string correctValue.
string correctValue = "Euro";
StringBuilder sb = new StringBuilder(final_response);
if (sb.ToString().Contains("\\u20ac"))
{
sb.Replace("\\u20ac", correctValue);
}
dynamic items = JObject.Parse(sb.ToString());
bool success = items.success;
string lowest = items.lowest_price;
string volume = items.volume;
string median = items.median_price;
// Create a test object of RootObject class and display it's values in cw.
RootObject r = new RootObject(success, lowest, volume, median);
Console.WriteLine("TEST OBJECT VALUES: Success: " + r.success + ", lPrice: " + r.lowest_price + ", vol: " + r.volume + ", mPrice: " + r.median_price + "\n");
// Calculation example
double num1 = Convert.ToDouble(r.FixComma(r.lowest_price,correctValue));
double num2 = Convert.ToDouble(r.FixComma(r.median_price, correctValue));
double result = num1 + num2;
Console.WriteLine("Result: " + result+"\n");
Console.WriteLine("Genuine Purity Fist");
Console.WriteLine(final_response);
Console.ReadKey();
}
}
public class RootObject
{
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
public RootObject(bool success, string lowest_price, string volume, string median_price)
{
this.success = success;
this.lowest_price = lowest_price;
this.volume = volume;
this.median_price = median_price;
}
public string FixComma(string value,string currency)
{
string correctValue = ".";
string correctValue2 = "";
StringBuilder sb = new StringBuilder(value);
if (sb.ToString().Contains(","))
{
sb.Replace(",", correctValue);
}
if (sb.ToString().Contains(currency))
{
sb.Replace(currency, correctValue2);
}
return sb.ToString();
}
}
}
Here is a link that explains how to downloade Json.NET https://www.nuget.org/packages/newtonsoft.json/.
One option is to use the JavaScriptSerializer class in the System.Web.Script.Serialization namespace.
For example:
RootObject obj = new JavaScriptSerializer().Deserialize<RootObject>(final_response);
Other options might be:
Do it yourself using reflection or manual parsing.
Third-party libraries like this one.
I would use JSON.NET for this. It provides a powerful and flexible way to deserialize and consume the data (and lets you change your mind about how to do it fairly easily later). It's also available as a NuGet package.
The simplest way would be to deserialize it into a dynamic or Object instance:
var object = JsonConvert.Deserialize<Object>(final_response);
var isSuccessful = object.success; // true or false
// ...
(You can replace object with dynamic too.)
If you want to deserialize to a class, create one:
class PriceData {
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
Then call .Deserialize<PriceData>(final_response) instead.
If you don't like lowercase-named or underscore-named variables (which is not the common style in C#), you can override the deserialization to specify which field to use for which C# property:
class PriceData {
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("lowest_price")]
public string LowestPrice { get; set; }
[JsonProperty("volume")]
public string Volume { get; set; }
[JsonProperty("median_price")]
public string MedianPrice { get; set; }
}