I’m running Visual Studio 2015 and Windows 8.1. I am struggling with a console application project.
The solution works fine in Visual Studio 2015, but when I try to compile it with mcs-compiler I get two errors (Kattis codetest use mcs-kompiler). Two external classes can not be found.
I'm getting the following error:
Program.cs(28,13): error CS0246: The type or namespace name Graph'
could not be found. Are you missing an assembly reference?
Program.cs(58,34): error CS0246: The type or namespace nameSolver'
could not b e found. Are you missing an assembly reference?
Compilation failed: 2 error(s), 0 warnings
The code is large so a I have pasted in just parts of it:
The Program class, where main is and the calls to ”Graph” and ”Solver” are made from:
Call in Program.cs:
-----------------------------------------------------------------------------
// first call:
var edges = CliquesToEdges(cliques);
sudokuColour.Graph graph = new Graph(81, edges);
string line = "";
string storeLine = "";
string puzzle = "";
.
.
.
// second call:
for (int i = 0; i < store.Count(); i++)
{
puzzle = store.ElementAt(i);
sudokuColour.Solver solver = new Solver(graph, 9);
int node = -1;
foreach (char c in puzzle)
{
----------------------------------------------------------------------------
//Beginning of "Graph" class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using sudokuColour;
namespace sudokuColour
{
public class Graph
{
.
.
----------------------------------------------------------------------------
//Beginning of "Solver" class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using sudokuColour;
namespace sudokuColour
{
public class Solver
{
private enum Result { Solved, Unsolved, Busted }
private readonly Graph graph;
----------------------------------------------------------------------------
What can the error be?
sudokuColour.Solver solver = new Solver(graph, 9);
The fact that you had to namespace-qualify it on the left probably means you should namespace-qualify it on the right too:
sudokuColour.Solver solver = new sudokuColour.Solver(graph, 9);
Alternatively, add a using directive at the top of the code file:
using sudokuColour;
or:
using Solver = sudokuColour.Solver;
likewise for:
sudokuColour.Graph graph = new Graph(81, edges);
If that still doesn't work: you're probably missing a project reference (or package reference, or assembly reference - but a project reference seems the most appropriate) between the two projects.
Related
I am using System.Device.Location in .Net.
It works well in my Windows system but when I use the same code in my MacBook version of visual studio, it's not compiling:
The type or namespace name 'Device' does not exist in the namespace 'System' (are you missing an assembly reference?) (CS0234)
Here is my code:
using Toonbank.Vendor.Entity.DashBoard;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Device.Location;
namespace Toonbank.Vendor.Bal
{
public class CalculateDistance
{
public double CalculateDistanceBetweenTwoPoints(CalculateDistanceClass obj)
{
//double latA = -31.997976f;
// double longA = 115.762877f;
// double latB = -31.99212f;
// double longB = 115.763228f;
var locA = new GeoCoordinate(obj.lat1, obj.lon1);
var locB = new GeoCoordinate(obj.lat2, obj.lon2);
double distance = locA.GetDistanceTo(locB); // me
double distanceToKm = distance / 1000;
return distanceToKm;
}
}
}
System.Device is not an installed package built into the framework, it's a public package on Nuget you can reference at will. This is important because different systems have a different "device" inputs and outputs, like GPIO on a Raspberry Pi.
You seem to want the System.Device.Location.Portable package.
I cannot understand why I am getting an error (using VS2017) for the code in below related to not finding the class ControlFlowGraph which is supposed to be part of the package Microsoft.CodeAnalysis.FlowAnalysis:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.FlowAnalysis;
namespace CodeAnalysisApp3
{
class Program
{
static async Task Main(string[] args)
{
// Attempt to set the version of MSBuild.
var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray();
var instance = visualStudioInstances[0];
Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects.");
// NOTE: Be sure to register an instance with the MSBuildLocator
// before calling MSBuildWorkspace.Create()
// otherwise, MSBuildWorkspace won't MEF compose.
MSBuildLocator.RegisterInstance(instance);
using (var workspace = MSBuildWorkspace.Create())
{
// Print message for WorkspaceFailed event to help diagnosing project load failures.
workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message);
var solutionPath = args[0];
Console.WriteLine($"Loading solution '{solutionPath}'");
// Attach progress reporter so we print projects as they are loaded.
var solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter());
Console.WriteLine($"Finished loading solution '{solutionPath}'");
// TODO: Do analysis on the projects in the loaded solution
CSharpParseOptions options = CSharpParseOptions.Default
.WithFeatures(new[] { new KeyValuePair<string, string>("flow-analysis", "") });
var projIds = solution.ProjectIds;
var project = solution.GetProject(projIds[0]);
Compilation compilation = await project.GetCompilationAsync();
if (compilation != null && !string.IsNullOrEmpty(compilation.AssemblyName))
{
var mySyntaxTree = compilation.SyntaxTrees.First();
// get syntax nodes for methods
var methodNodes = from methodDeclaration in mySyntaxTree.GetRoot().DescendantNodes()
.Where(x => x is MethodDeclarationSyntax)
select methodDeclaration;
foreach (MethodDeclarationSyntax node in methodNodes)
{
var model = compilation.GetSemanticModel(node.SyntaxTree);
node.Identifier.ToString();
if (node.SyntaxTree.Options.Features.Any())
{
var graph = ControlFlowGraph.Create(node, model); // CFG is here
}
}
}
}
}
private class ConsoleProgressReporter : IProgress<ProjectLoadProgress>
{
public void Report(ProjectLoadProgress loadProgress)
{
var projectDisplay = Path.GetFileName(loadProgress.FilePath);
if (loadProgress.TargetFramework != null)
{
projectDisplay += $" ({loadProgress.TargetFramework})";
}
Console.WriteLine($"{loadProgress.Operation,-15} {loadProgress.ElapsedTime,-15:m\\:ss\\.fffffff} {projectDisplay}");
}
}
}
}
However, when I compile the above code I am getting the following error message with VS2017:
1>Program.cs(67,41,67,57): error CS0103: The name 'ControlFlowGraph' does not exist in the current context
1>Done building project "CodeAnalysisApp3.csproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
Version used:
Microsoft (R) Visual C# Compiler version 4.8.3761.0
for C# 5
Based on my test, I find I can use class ControlFlowGraph.
I installed the following nugetpackage.
Microsoft.CodeAnalysis
Microsoft.Build.Locator
Then, you will see the following result.
Besides, I used .net framwork 4.6.1.
I was able to solve the problem when I used roslyn CodeAnalysis packages with the proper versions:
CodeAnalysis.CSharp.Workspaces (3.4.0)
CodeAnalysis.FlowAnalysis.Utilities (2.9.6)
CodeAnalysis.Workspaces.MSBuild (3.4.0)
The target framework is .NETFramework 4.7.2
A link to a closed issue created for this question on roslyn Github repo is here
I am programming certificate generation, but I am experiancing something like assembly namespace conflict between BouncyCastle and ITextSharp-LGPL-4.1.6.
So I tried to add an alias to the BouncyCastle library that I am using, and tried explicit conversion, but nothing worked.
return (BouncyCastleCrypto::Org.BouncyCastle.X509.X509Certificate)cert.Generate(pair.Private);
And the result is that I get an error:
CS0029 Cannot implicitly convert type 'Org.BouncyCastle.X509.X509Certificate [C:\XXX\packages\BouncyCastle.1.8.4\lib\BouncyCastle.Crypto.dll]' to 'Org.BouncyCastle.X509.X509Certificate [C:\XXX\packages\iTextSharp-LGPL.4.1.6\lib\iTextSharp.dll]' Project C:\xxx\src\MyCode.cs
I have no idea what to do now, I am out of options.
EDIT1:
Question is not about accessing the type itself, its about calling the method of the type.
I have this part of code:
BouncyCastleCrypto::Org.BouncyCastle.X509.X509V3CertificateGenerator cert = new BouncyCastleCrypto::Org.BouncyCastle.X509.X509V3CertificateGenerator();
And then I have this part of code:
return cert.Generate(pair.Private);
Which gives me the error. How am I supposed to clarify which assembly I am using when this is just method call?
EDIT2:
Okay so I am pasting whole file here :
extern alias BouncyCastleCrypto;
using BouncyCastleCrypto.Org.BouncyCastle.Crypto.Operators;
using BouncyCastleCrypto.Org.BouncyCastle.Asn1.Pkcs;
using BouncyCastleCrypto.Org.BouncyCastle.Asn1.X509;
using BouncyCastleCrypto.Org.BouncyCastle.Crypto;
using BouncyCastleCrypto.Org.BouncyCastle.Crypto.Generators;
using BouncyCastleCrypto.Org.BouncyCastle.Crypto.Prng;
using BouncyCastleCrypto.Org.BouncyCastle.OpenSsl;
using BouncyCastleCrypto.Org.BouncyCastle.Pkcs;
using BouncyCastleCrypto.Org.BouncyCastle.Security;
using XXXX.ViewModels;
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using BouncyCastleCrypto.Org.BouncyCastle.X509;
using BouncyCastleCrypto.Org.BouncyCastle.Math;
namespace XXXX.Helpers
{
public static class PKIHelper
{
public static Org.BouncyCastle.X509.X509Certificate GenCert(CertInfo info)
{
RsaKeyPairGenerator _rsa = new RsaKeyPairGenerator();
SecureRandom _random = new SecureRandom();
_rsa.Init(new KeyGenerationParameters(_random, info.rsa_strength));
AsymmetricCipherKeyPair _pair = _rsa.GenerateKeyPair();
X509Name _cert_name = new X509Name("CN=" + info.name);
BigInteger _serialnumber = BigInteger.ProbablePrime(120, new Random());
BouncyCastleCrypto::Org.BouncyCastle.X509.X509V3CertificateGenerator _cert = new BouncyCastleCrypto::Org.BouncyCastle.X509.X509V3CertificateGenerator();
_cert.SetSerialNumber(_serialnumber);
_cert.SetSubjectDN(_cert_name);
_cert.SetIssuerDN(_cert_name);
_cert.SetNotBefore(info.begin_date);
_cert.SetNotAfter(info.expire_date);
_cert.SetSignatureAlgorithm("SHA1withRSA");
_cert.SetPublicKey(_pair.Public);
_cert.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
new AuthorityKeyIdentifier(
SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_pair.Public),
new GeneralNames(new GeneralName(_cert_name)), _serialnumber));
_cert.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth }));
return _cert.Generate(_pair.Private); // here's error
}
}
}
Okay so the thing is that I was pretty sure I was using the right type as return type of the GeneratePKI method , which was Org.BouncyCastle.X509.X509Certificate, but in reality the Org.BouncyCastle.X509.X509Certificate was from iTextSharp library, and so the compiler thought it has to covnert it implicitly. When I added the alias before the method return type BouncyCastleCrypto::Org.BouncyCastle.X509.X509Certificate, it all magically started compiling again. Thanks #devNull, for not abandoning me.
I am new in C#, and I have spent the entire night just trying to compile my code. I am not asking for a logic, but rather some help with compiling using csc.
I have an app that uses System.Net.Http, and I am trying to get it compiled into an executable using csc, but I always get the following result:
C:\Users\farao\Documents\Visual Studio 2017\source\repos\SimpleWebCrawlerApp\SimpleWebCrawlerApp>csc Program.cs
Microsoft (R) Visual C# Compiler version 2.6.0.62329 (5429b35d)
Copyright (C) Microsoft Corporation. All rights reserved.
Program.cs(4,18): error CS0234: The type or namespace name 'Http' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)
C:\Users\farao\Documents\Visual Studio 2017\source\repos\SimpleWebCrawlerApp\SimpleWebCrawlerApp>
However, I can compile in Visual Studio 2017, but I do need to compile it using csc for quick distribution.
I tried almost everything from this link
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Collections;
using System.Text.RegularExpressions;
namespace SimpleWebCrawlerApp
{
class Program
{
internal static int SUCCESS = 0;
internal static int FAIL = -1;
static void Main(string[] args)
{
TextWriter errorWriter = Console.Error;
if (args.Length != 2)
{
errorWriter.WriteLine("usage: <program_name>.exe <http/https url> <number of hops>");
}
else
{
if (IsValidUrl(args[0]))
{
int hops;
if (int.TryParse(args[1], out hops))
{
new HTTPCrawler(args[0], hops).Crawl();
Environment.Exit(SUCCESS);
}
errorWriter.WriteLine("not a valid integer for number of hops");
}
else
{
errorWriter.WriteLine("observe proper http/https protocol");
}
}
Environment.Exit(FAIL);
}
I solved my problem thanks to UnholySheep.
csc /r:System.Net.Http.dll Program.cs
References:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/reference-compiler-option
https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx
I'm trying to write a program that sorts images in specific folder by ther dimensions and moves little images to another folder via simple .NET console application. I decided to use System.Drawing.Image class to get the image dimentions from an image file. But I face following error:
The type or namespace name 'Image' could not be found (are you missing
a using directive or an assembly referrence?)
What exactly did I do wrong and why it doesn't see this class?
Here are the complete code of my program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
namespace ImageSort
{
class Program
{
static void Main(string[] args)
{
string targetPath = #"d:\SmallImages";
string[] files = Directory.GetFiles(#"d:\Images");
foreach (string path in files)
{
if (File.Exists(path))
{
Image newImage = Image.FromFile(path);
var Width = (int)(newImage.Width);
var Height = (int)(newImage.Height);
if (Width * Height < 660000) {
System.IO.File.Move(path, targetPath);
}
}
}
}
}
}
You need to add a reference : System.Drawing.dll.
In Solution Explorer, right-click on the References node and choose Add Reference and find System.Drawing.dll.
The answer to this issue for .NET Core 3.1 is to simply install System.Drawing.Common from NuGet.