I am planning to use HTTP PUT in a WPF .NET 4.7.2 application and before I get started I wanted to quickly test putting data using a console .NET 4.7.2 application but I am getting an error on var response = client.PutAsJsonAsync("api/person", p).Result;
Error:
Error CS1061 'HttpClient' does not contain a definition for 'PutAsJsonAsync' and no accessible extension method 'PutAsJsonAsync' accepting a first argument of type 'HttpClient' could be found (are you missing a using directive or an assembly reference?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary;
using System.Threading;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
namespace HTTP
{
class Program
{
static void Main(string[] args)
{
using (var client = new HttpClient())
{
person p = new person { name = "Sourav", surname = "Kayal" };
client.BaseAddress = new Uri("http://localhost:1565/");
var response = client.PutAsJsonAsync("api/person", p).Result;
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
else
Console.Write("Error");
}
Console.ReadKey();
}
}
}
You can install the Newtonsoft.Json NuGet package and use it this way instead :
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using (HttpClient client = new HttpClient())
{
Person p = new Person { name = "Sourav", surname = "Kayal" };
string jsonObject = JsonSerializer.Serialize(p);
var content = new StringContent(jsonObject, Encoding.UTF8, "application/json");
client.BaseAddress = new Uri("http://localhost:1565/");
var response = client.PutAsync("api/person", content).Result;
if (response.IsSuccessStatusCode) Console.Write("Success");
else Console.Write("Error");
}
Here is the Microsoft documentation (.NET Framework 4.7.2) :
HttpClient.PutAsync Method
Not sure the System.Net.Http.Json.HttpClientJsonExtensions.PutAsJsonAsync method is available for .NET Framework 4.7.2...
Related
Hi I am trying to analyze my CsProj using Roslyn. I'm having issues finding my solution. This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.MSBuild;
namespace Test
{
class Programm
{
static async Task Main(string[] args)
{
SourceAnalyzer sa = new SourceAnalyzer();
string path = #"C:\Users\lhafer\source\repos\Farm\Farm\Farm.csproj";
using (var workspace = MSBuildWorkspace.Create())
{
var project = await workspace.OpenProjectAsync(path);
var compilation = await project.GetCompilationAsync();
}
//sa.Analyze(path).Wait();
}
}
}
the Exception says:
System.Reflection.ReflectionTypeLoadException: "Unable to load one or more of the requested types.
Could not load file or assembly 'Microsoft.Build, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Thank you for your help!
I am following the new Azure.ResourceManager SDK examples here.
I'm not seeing classes I'd expect to see in Azure.ResourceManager.Resources. Specifically, ArmDeploymentCollection and ResourceGroupResource doesn't have a GetArmDeployments() method.
Azure.ResourceManager installed is Azure.ResourceManager.1.0.0. I'm targeting .NET framework 4.8.
I've tried uninstalling/re-installing Azure.ResourceManager several times, but doesn't change anything.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.IO;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.KeyVault;
using System.Threading;
using Azure;
using Azure.Identity;
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Resources.Models;
public static void Initialize()
{
try
{
// Authenticate
var credentials = new DefaultAzureCredential();
await RunSample(credentials);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
public static async Task RunSample(TokenCredential credential)
{
try
{
var deploymentName = "bradDeployment";
var rgName = "rg-percipience-test-002";
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var templateJson = Utilities.GetArmTemplate("ArmTemplate.json");
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await armClient.GetDefaultSubscriptionAsync();
ResourceGroupCollection rgCollection = subscription.GetResourceGroups();
// With the collection, we can create a new resource group with an specific name
AzureLocation location = AzureLocation.EastUS;
ArmOperation<ResourceGroupResource> lro = await rgCollection.CreateOrUpdateAsync(WaitUntil.Completed, rgName, new ResourceGroupData(location));
ResourceGroupResource resourceGroup = lro.Value;
Utilities.Log("Created a resource group with name: " + rgName);
// Create a deployment for an Azure App Service via an ARM
// template.
Utilities.Log("Starting a deployment for an Azure App Service: " + deploymentName);
// First we need to get the deployment collection from the resource group
ArmDeploymentCollection armDeploymentCollection = resourceGroup.GetArmDeployments();
// Use the same location as the resource group
// Passing string to template and parameters
var input = new ArmDeploymentContent(new ArmDeploymentProperties(ArmDeploymentMode.Incremental)
{
Template = BinaryData.FromString(File.ReadAllText("storage-template.json")),
Parameters = BinaryData.FromString(File.ReadAllText("storage-parameters.json"))
});
ArmOperation<ArmDeploymentResource> lro2 = await ArmDeploymentCollection.CreateOrUpdateAsync(WaitUntil.Completed, deploymentName, input);
ArmDeploymentResource deployment = lro2.Value;
Utilities.Log("Completed the deployment: " + deploymentName);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
await (await resourceGroups.StartDeleteAsync(rgName)).WaitForCompletionAsync();
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
I resolved the issue by adding a reference to Azure.ResourceManager.Resources.dll. Not sure why this reference isn't added when the nuget package is installed.
I'm currently porting over my project from the .NET Framework to .NET Standard 2.0, and will be feeding the nuget packages to a .NET Core application. With that said I'm currently having issues on handling this last issue which is that i'm unable to use the SqlQuery method using the .NET Standard framework. Below is the error i'm receiving as well as the libraries being used and where I was originally using the SqlQuery method. I have seen various implementations with FromSql however I don't believe this works for me because I want to return an int and FromSql returns TEntity.
'DatabaseFacade' does not contain a definition for 'SqlQuery' and no
accessible extension method 'SqlQuery' accepting a first argument of
type 'DatabaseFacade' could be found (are you missing a using
directive or an assembly reference?)
using Microservices.LibCore.Core;
using Microservices.LibCore.Core.Base.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Reflection;
public static List<object> setLegacyKey(DbContext dbContext, ServiceObject obj)
{
var keyValuesFound = new List<object>();
var keyProperties = getKeyProperties(obj);
foreach (var key in keyProperties)
{
string sql = "select " + getKeyColumnName(key) + " from " + getTableName(obj) + " where global_id=#p0";
List<object> result = dbContext.Database.SqlQuery(key.PropertyType, sql, obj.Id).ToListAsync().Result;
if (result.Count == 0)
{
throw new ServiceException(ServiceError.ERROR_CODE.INVALID_REQUEST, String.Format("Invalid {1}.ID ({0})", obj.Id, obj.GetType().Name));
}
var keyValue = result.FirstOrDefault();
key.SetValue(obj, keyValue);
keyValuesFound.Add(keyValue);
}
return keyValuesFound;
}
I'm fairly new to c# and writing a simple selenium code which will go onto www.asos.com. I then click on the country on the right hand side by finding the xpath. When I click on the country I want to change the country to 'india' and the currency to 'USD', and then select my preference.
I'm getting exception for driver.FindElement, SelectElement, SelectByValue previously when using java I wasn't getting these exceptions.
Exception I see for driver = The name driver doesn't exist in the current context
SelectElement = the type or namespace name 'SelectElement' could not be found
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace Exercise1
{
class Program
{
static void Main(string[] args)
{
IWebDriver webDriver = new ChromeDriver(#"Path to my chrome driver defined here");
webDriver.Navigate().GoToUrl("www.asos.com");
driver.FindElement(By.XPath("//*[#id="chrome - header"]/header/div[2]/div/ul/li[3]/div/button')]")).Click();
var country = driver.FindElement(By.Id("country"));
var select_country = new SelectElement(country);
select_country = SelectByValue("India");
var currency = driver.FindElement(By.Id("currency"));
var select_currency = new SelectElement(currency);
select_currency = SelectByValue("$ USD");
driver.FindElement(By.XPath("//*[#id="chrome - header"]/header/div[5]/div[2]/div/section/form/div[3]/button")).Click();
}
}
driver.FindElement(By.XPath("//*[#id="chrome - header"]/header/div[5]/div[2]/div/section/form/div[3]/button")).Click();
The erro in quotation marks, try:
driver.FindElement(By.XPath("//*[#id='chrome - header']/header/div[5]/div[2]/div/section/form/div[3]/button")).Click();
Use the value of the option in the html. Also call the select on the select element. For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace Exercise1
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver= new ChromeDriver(#"Path to my chrome driver defined here");
driver.Navigate().GoToUrl("www.asos.com");
driver.FindElement(By.XPath("//*[#id='chrome - header']/header/div[2]/div/ul/li[3]/div/button')]")).Click();
var country = driver.FindElement(By.Id("country"));
var select_country = new SelectElement(country);
select_country.SelectByValue("IN");
var currency = driver.FindElement(By.Id("currency"));
var select_currency = new SelectElement(currency);
select_currency.SelectByValue("2");
driver.FindElement(By.XPath("//*[#id='chrome - header']/header/div[5]/div[2]/div/section/form/div[3]/button")).Click();
}
}
You may also want to throw in some waits to give the page time to load.
How to create NAMED-PIPE in .NET-4 in your C# application?
Here is a piece of code to create a Named Pipe client, it is lifted from an answer to a previous question I answered on communicating between C++ and C# using Named Pipes
using System;
using System.Text;
using System.IO;
using System.IO.Pipes;
namespace CSPipe
{
class Program
{
static void Main(string[] args)
{
NamedPipeClientStream pipe = new NamedPipeClientStream(".", "HyperPipe", PipeDirection.InOut);
pipe.Connect();
using (StreamReader rdr = new StreamReader(pipe, Encoding.Unicode))
{
System.Console.WriteLine(rdr.ReadToEnd());
}
Console.ReadKey();
}
}
}
The easiest way is using WCF:
var binding = new System.ServiceModel.NetNamedPipeBinding(System.ServiceModel.NetNamedPipeSecurityMode.None)