ApiController could not be found - c#

Based on this video https://www.youtube.com/watch?v=IVvJX4CoLUY I have add the using System.Web; using System.Web.Http; but i still get the error state that apicontroller could no found, and so on, below picture is the error I face:
below is my code :
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Collections.Generic;
namespace UploadToServer.Server.Controllers
{
public class UploadsController : ApiController
{
[Route("api/Files/Upload")]
public async Task<string> Post()
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var fileName = postedFile.FileName.Split('\\').LastOrDefault().Split('/').LastOrDefault();
var filePath = HttpContext.Current.Server.MapPath("~/Uploads/" + fileName);
postedFile.SaveAs(filePath);
return "/Uploads/" + fileName;
}
}
}
catch (Exception exception)
{
return exception.Message;
}
return "no files";
}
}
}
Anyone can share me ideas?

You are missing the references in your project for those libraries. As per svdoever you can add the package Microsoft.AspNet.WebApi through NuGet to fix this. For instructions on how to use NuGet, please click here

Your question have nothing to do with Xamarin.Forms but with WEB.API. Your Xamarin.Forms project cannot and should not contain any WEB.Api controllers. Your server side code should be in a separate project. The easiest way to do so is to create a separate project with a specific template.Luckily Microsoft has a very easy to follow guides:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
However I would recommend you to use Asp.NET Core instead:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api

You getting this error because packages required to run API are not installed.
Manually you have to download this package from nuget.org.
Follow below steps -
Check whether Nuget.ORG listed in Package Source.
Tools -> Nuget Package Manager -> Package Manager Setting -> Package Sources.
If Nuget is not listed in Package Source then Add source as "http://nuget.org" and update.
Tools -> Nuget Package Manager -> Package Manager Console
Select Package source as "Nuget" and Click Restore
Same can be done by Right Click Your Solution file -> Manage Nuget Packages for solution.
Select Nuget in Package Source and restore.
Required packages will be downloaded from nuget.org

Related

'AnsiConsole' does not contain a definition for 'Live'

I am using Spectre.Console extension for C# Console Application. And I wanted to use Live-Display module of Spectre.Console but I encoutered following problem:
'AnsiConsole' does not contain a definition for 'Live'
Here is my code, or better say, part of it which contains problem (... are parts which aren't required in sample, so during testing/debugging/modification remove them)
using System;
using Spectre.Console;
...
namespace ConsoleApp2
{
class Program
{
...
static void Main(...)
{
AnsiConsole.Live(Clock())
.Start(ctx =>
{
ctx.Refresh();
Thread.Sleep(1000);
});
...
}
...
public static void Clock()
{
Console.WriteLine(DateTime.Now.ToString());
}
...
}
...
}
Additional information
I installed extension using NuGet package manager with following command: PM> Install-Package Spectre.Console, not with dotnet add package Spectre.Console as indicated in docs, but latter option was unavailable for some reason so I used first.
I am using Visual Studio 2019 Community Edition
I am using .NET Framework 4.7.2
Ok, so thanks to #JonSkeet's and #yaakov's comments, I tried installing latest pre-release version 0.39.1-preview-0.31 instead of latest stable version 0.39 and it worked.
Looks like problem was with versions.

Trying to make HttpTrigger pass a blob

I'm trying to make a HTTP Trigger in Visual Studio Code which just need to make a file and pass it to blob storage, but I get an error saying: "The type or namespace 'Blob' could not be found"
Here is a full working example. I think you are just missing a using / referece a nuget package.
Reference Nuget package Microsoft.Azure.WebJobs.Extensions.Storage
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Blob;
namespace SampleFunctions
{
public static class Http2BlobFunction
{
[FunctionName("Http2BlobFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
[Blob("myblobcontainer/{rand-guid}.txt", FileAccess.Write)] CloudBlockBlob blob,
ILogger log)
{
log.LogInformation("Received file upload request");
var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
await blob.UploadTextAsync(requestBody);
return new OkObjectResult(blob.Name);
}
}
}
If you VS Code to develop Azure Function V2.0, you need to manually install package vai .NET.CLI. Since you use storage binding, please run the command dotnet add package Microsoft.Azure.WebJobs.Extensions.Storage --version 3.0.7 to install the package. For more details, please refer to the document.
You can also use the azure CLI to install extensions.
func extensions install
Finally, you can use the portal

Is it possible to install a local version of a package at runtime and use said local package?

As part of trying to test a NuGet package with a Console application, is it possible to have the console application get the latest version of said NuGet package programmatically, and then use said package to call various methods and what not? This is the flow that I'm trying to achieve...
A NuGet package is created locally (already done as part of a build process)
A console application installs this package
The same console application calls a few methods that are inside this package (if this uses reflection insdie the console app to achieve this it isn't an issue)
How can this be achieved? I've tried the following code using the NuGet.Core & NuGet.Protocol NuGet packages...
// exception thrown for trying to resolving newtonsoft
IPackageRepository packageRepository = new NuGet.LocalPackageRepository(directoryPath);
PackageManager pm = new PackageManager(packageRepository, GetExecutingAssemblyDirectory());
pm.InstallPackage("package_id", SemanticVersion.Parse("package_version"));
NuGet.Common.ILogger logger = new Logger();
IEnumerable<LocalPackageInfo> packageInfos = LocalFolderUtility.GetPackagesV2(directoryPath, logger);
foreach (LocalPackageInfo lpi in packageInfos)
{
// no obvious way to actually install the package
}
// never more than zero packages
var localRepo = new LocalPackageRepository(directoryPath);
var packages = localRepo.GetPackages();
if (packages?.Count() > 0)
{
var packageManager = new PackageManager(localRepo, GetExecutingAssemblyDirectory());
packageManager.InstallPackage(packages.ElementAt(0).Id);
}
I haven't been able to get any of those pieces of code to work. Is this actually possible? Would I have to look at using 2 Console apps (one to install into the other, which then does the calling of methods), and if so how would this be done?

What is the reference for PowerShell in .NET?

I tried to run a PowerShell script in C#. But it throws and error :
PowerShell doesn't available in current context.
I searched in google but i didn't get the solution, please help. This is my code :
string text = System.IO.File.ReadAllText(#"C:\Program Files (x86)\Backup Reporter\Required\edit_website.ps1");
using (PowerShell PowerShellInstance = PowerShell.Create())
{
// use "AddScript" to add the contents of a script file to the end of the execution pipeline.
// use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
PowerShellInstance.AddScript(text);
if (PowerShellInstance.Streams.Error.Count > 0)
{
Console.Write("Error");
}
Console.ReadKey();
}
Download and Add the packages of System.Management.Automation and System.Management.Automation.Runspaces from VS Nuget Manager to your project.
https://powershell.org/forums/topic/executing-powershell-from-c/
PowerShell class exists in Windows PowerShell SDK 1.1.0 that you to your project with this NuGet package : https://www.nuget.org/packages/System.Management.Automation/
PM> Install-Package System.Management.Automation -Version 6.2.0
You need to download System.Management.Automation and attach it to your project:
https://www.nuget.org/profiles/PowerShellTeam

create nuget package fails with 'Path is not of a legal form'

In a post build step we create nuget packages. For some reasons this always fails on my machine, while it works on other developers machines.
The command executed is:
nuget.exe pack "$(ProjectPath)" -Properties Configuration=$(ConfigurationName) -OutputDir "$(ProjectDir)..\Apps"
The output i get is:
Packing files from ''.
Using 'Organisation.AppName.Modules.Kcs.nuspec' for metadata.
The path is not of a legal form.
For other developers the first line contains the directory. What can be the reason it is working differently on my box? Are there options i can set to change this behavior?
Edit:
I downloaded the nuget source and found the point things start to go wrong. With a small test program i can simulate it:
using System;
using Microsoft.Build.Evaluation;
namespace CheckTarget
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("usage: CheckTarget projectfile.csproj");
Console.WriteLine();
return;
}
string path = args[0];
var project = new Project(path);
Console.WriteLine("TargetDir = {0}", project.GetProperty("TargetDir") != null ? project.GetProperty("TargetDir").EvaluatedValue : string.Empty);
Console.WriteLine("TargetPath = {0}", project.GetProperty("TargetPath").EvaluatedValue);
Console.ReadKey();
}
}
}
On my machine the targetdir is null, on another machine the targetdir points to valid directory.
Use property Platform to -Properties parameter in nuget program
-Properties Platform=$(Platform)
where $(Platform) is one of your project platform (defined in csproj file, typically x86, 'Any CPU', ..).
ie in your case, run something like:
nuget.exe pack "$(ProjectPath)" -Properties Configuration="$(ConfigurationName)" Platform="$(Platform)" -OutputDir "$(ProjectDir)..\Apps"
Finally found the answer. This thread helped me locate the problem:
http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/d3c6e2de-1e87-49c2-b059-df074868e315/
On my machine there was an environment variable 'platform' with value 'BWS'. Deleted it and things are working!
I had the same problem basically it was an old nuget version that I carried in my source control, I deleted the .nuget folder then I uninstalled nuget from visual studio, by selecting
tools > extensions & updates,
select nuget & uninstall and then do the same process but for Installing it, just make sure you al searching in the "online" repository.
I had to update the Nuget Manager from Updates And Extensions. Restarted VS, and it worked fine.
For me the problem was that no .dll was inside the Debug folder and without the -properties Configuration=Release option nuget usually tries to find a dll in the Debug folder.
Running nuget pack manually gave me an useful error message. Running it as post build event I got the same obscure error message as you.

Categories

Resources