Error on all Program.cs files on eShopOnContainers, microsoft microsevice based implmentation - microservices

Severity Code Description Project File Line Suppression State Error CS0260 Missing partial modifier on declaration of type 'Program'; another partial declaration of this type exists WebStatus D:\GitHub\eShopOnContainers\src\Web\WebStatus\Program.cs 123 Active
...
(int httpPort, int grpcPort) GetDefinedPorts(IConfiguration config)
{
var grpcPort = config.GetValue("GRPC_PORT", 5001);
var port = config.GetValue("PORT", 80);
return (port, grpcPort);
}
public class Program
{
public static string Namespace = typeof(Startup).Namespace;
public static string AppName
=Namespace.Substring(Namespace.LastIndexOf('.',Namespace.LastIndexOf('.') - 1) + 1);
}
this is the program found in Program.cs, look that it doesn't have a defined namespace, there are a bunch of functions defined as 'GetDefinedPorts'. I am following the Microsoft microservice implementation example https://github.com/dotnet-architecture/eShopOnContainers

This looks like a bug in Visual Studio 2022. It doesn't happen in 2019. They are also in the middle of converting the solution to dot net 6 so things may get a little more stable after that work is complete.

Related

Unity cannot build GRPC Project for UWP with IL2CPP Backend

Here, or here for a complete version, you can find a sample GRPC "Hello World" project for Unity. Only the first version, that is built for Unity and wrapped in a DLL is working perfectly fine in Unity IDE and on Standalone build. The Raw Grpc.Core files are referencing everything correctly in IDE but they have Marshaling problem.
Unfortunately, it cannot get build for UWP with IL2CPP backend. Unity builds the project and creates a .sln project. But Visual Studio always gives LNK2001 for GRPC properties on the final compilation.
Here are first error codes:
LNK2001 unresolved external _grpccsharp_init#0
LNK2001 unresolved external _grpccsharp_shutdonw#0
LNK2001 unresolved external _grpccsharp_version_string#0
...
Ok, thanks to #Sunius, I digged into it a little bit more. There are some points, I am going to add to the question:
There are two methods regarding referencing extern methods in GRPC C# package. They are named static and shared libs.
internal class DllImportsFromStaticLib
{
private const string ImportName = "__Internal";
[DllImport(ImportName)]
public static extern void grpcsharp_init();
[DllImport(ImportName)]
public static extern void grpcsharp_shutdown();
...
}
and
internal class DllImportsFromSharedLib
{
private const string ImportName = "grpc_csharp_ext";
[DllImport(ImportName)]
public static extern void grpcsharp_init();
[DllImport(ImportName)]
public static extern void grpcsharp_shutdown();
...
}
I tried to test it with the shared one, I got another linking error file which is a little bit different.
LNK2001 unresolved external _dlopen#8
LNK2001 unresolved external _dlsym#8
...
In two separate methods, extern methods are getting connected to the internal interface:
public NativeMethods(DllImportsFromStaticLib unusedInstance)
{
this.grpccsharp_init = DllImportsFromStaticLib.grpccsharp_init;
this.grpccsharp_shutdown = DllImportsFromStaticLib.grpccsharp_shutdonw;
...
}
and
public NativeMethods(DllImportsFromSharedLib unusedInstance)
{
this.grpccsharp_init = DllImportsFromSharedLib.grpccsharp_init;
this.grpccsharp_shutdown = DllImportsFromSharedLib.grpccsharp_shutdonw;
...
}
And which method will get called is defined here:
private static NativMethods LoadNativeMethodsUnity()
{
switch(PlatformApis.GetUnityRuntimePlatform())
{
case "IPhonePlayer":
return new NativeMethods(new NativeMethods.DllImportsFromStaticLib());
default:
return new NativeMethods(new NativeMethods.DllImportsFromSharedLib());
}
}
Some updates:
Thanks to #jsmouret, there is Stub.c file in his Grpc Github with fake methods, so Linker does not complain about Grpc_init methods anymore.
Next Error: dlopen, dlsym, dlerror:
First, I tried to use the same, Stub technique, but it did not help in this case, or maybe I did it wrong.
Thanks to #Sunius, I commented out all of "__Internal" dll import codes. So I am not getting any dlopen, dlsym, and dlerror errors.
Next Error: It happens from inside application, not the visual studio debugger. It tells me: "exception: to marshal a managed method, please add an attribute named 'MonoPInvokeCallback' to the method definition."
exception: error loading the embedded resource "Grpc.Core.roots.pem"
and
exception: To marshal a managed method, please add an attribute named 'MonoPInvokeCallback' to the method definition.
After I googled it, I know my options, but the question it, for which method should I do that?!
Thanks to my colleague Alice, #Sunius and #jsmouret, at the end, grpc works on UWP on Unity Platform through this steps:
Download Grpc.Core folder from Google Grpc Github.
Download Grpc Unity plugin from their official site.
Copy the runtime folder to your Grpc.Core folder. Please remove Grpc.Core.dll that you get from Grpc Unity Plugin, since we are using their source code.
Grpc should be in a folder called, Plugins in Unity, otherwise it will not be recognized.
Include this file in your runtime folder.
Include the Stub also from the Unity Plugin Inspector for WSA.
Find runtime .dll for Windows and include them in WSA from Unity Plugin Inspector.
By now, you should be getting _dlopen error.
Search through your Unity Solution with an IDE for "__Internal". There are not so many places, but comment them out. Also some methods that are depended on "__Internal"s, like dlopen and dlsym.
By now, you are not getting anymore build error but you need to make Grpc work.
Search for something like "DefaultSslRootsOverride" and comment out like below:
internal static class DefaultSslRootsOverride
{
const string RootsPemResourceName = "Grpc.Core.roots.pem";
static object staticLock = new object();
/// <summary>
/// Overrides C core's default roots with roots.pem loaded as embedded resource.
/// </summary>
public static void Override(NativeMethods native)
{
lock (staticLock)
{
//var stream = typeof(DefaultSslRootsOverride).GetTypeInfo().Assembly.GetManifestResourceStream(RootsPemResourceName);
//if (stream == null)
//{
// throw new IOException(string.Format("Error loading the embedded resource \"{0}\"", RootsPemResourceName));
//}
//using (var streamReader = new StreamReader(stream))
//{
// var pemRootCerts = streamReader.ReadToEnd();
// native.grpcsharp_override_default_ssl_roots(pemRootCerts);
//}
}
}
}
Search for something like "static void HandWrite" and add an attribute like something in below:
[MonoPInvokeCallback(typeof(GprLogDelegate))]
private static void HandleWrite(IntPtr fileStringPtr, int line, ulong threadId, IntPtr severityStringPtr, IntPtr msgPtr)
{
try
{
var logger = GrpcEnvironment.Logger;
string severityString = Marshal.PtrToStringAnsi(severityStringPtr);
string message = string.Format("{0} {1}:{2}: {3}",
threadId,
Marshal.PtrToStringAnsi(fileStringPtr),
line,
Marshal.PtrToStringAnsi(msgPtr));
switch (severityString)
{
case "D":
logger.Debug(message);
break;
case "I":
logger.Info(message);
break;
case "E":
logger.Error(message);
break;
default:
// severity not recognized, default to error.
logger.Error(message);
break;
}
}
catch (Exception e)
{
Console.WriteLine("Caught exception in native callback " + e);
}
}
I guess, you are done. In case, it did not work for your UWP, let me know, maybe I can help. :)
It looks like your plugin uses "__Internal" P/Invoke to call those native functions:
https://github.com/grpc/grpc/blob/befc7220cadb963755de86763a04ab6f9dc14200/src/csharp/Grpc.Core/Internal/NativeMethods.Generated.cs#L542
However, the linker cannot locate those functions and thus fails. You should change that code to either specify the DLL file name where the functions are implemented, or drop the source files with definitions for those functions into your Unity project. Or, if that code path isn't actually invoked (since you said it works on the standalone player), #ifdef it out from UWP build.
You can find more information about "__Internal" P/Invoke here:
https://docs.unity3d.com/Manual/windowsstore-plugins-il2cpp.html

Cannot suppress certain warning globally

I have VS2013 with Code Analysis turned on. I want to suppress one type of message globally, so I have following code in GlobalSuppressions.cs
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Scope = "namespace", Target = "MyProject.MyNamespace")]
But my function name contains underscore still got warned/errored by VS.
[TestMethod()]
public void Do_Something_Successfully_Test()
{
}
Any idea why?

Error creating instance of C# class in F# script file

I have the following C# class that I would like to make use of in F#
using System;
using System.Collections.Generic;
using System.Text;
namespace DataWrangler.Structures
{
public enum Type { Trade = 0, Ask = 1, Bid = 2 }
public class TickData
{
public string Security = String.Empty;
public uint SecurityID = 0;
public object SecurityObj = null;
public DateTime TimeStamp = DateTime.MinValue;
public Type Type;
public double Price = 0;
public uint Size = 0;
public Dictionary<string, string> Codes;
}
}
I would like to create an instance of it in F#. The code I am using to do this is in an f# script file
#r #"C:\Users\Chris\Documents\Visual Studio 2012\Projects\WranglerDataStructures\bin\Debug\WranglerDataStructures.dll"
open System
open System.Collections.Generic;
open System.Text;
open DataWrangler.Structures
type tick = TickData // <- mouse over the "tick" gives me a tooltip with the class structure
// it bombs out on this line
let tickDataTest = tick(Security = "test", TimeStamp = DateTime(2013,7,1,0,0,0), Type = Type.Trade, Price = float 123, Size = uint32 10 )
The error I get is:
error FS0193: internal error: Could not load file or assembly 'file:///C:\Users\Chris\Documents\Visual Studio 2012\Projects\WranglerDataStructures\bin\Debug\WranglerDataStructures.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format.
I have checked the file paths and they seem to be correct. I can mouse over the 'type tick' and it gives me the structure of the C# object. So It seems to be finding the C# code. Can anyone tell me what I am doing wrong here? Syntax? Still very new to C# -> F# introp
There are several things to check here:
Make sure that fsi.exe is running in a bit mode that is compatible with your WranglerDataStructures.dll. You run fsi.exe as a 64, or 32 bit process by setting a flag in the Visual Studio Options, under F# Tools -> F# Interactive -> 64-bit F# Interactive. You can usually avoid these types of problems by setting your C# assembly to compile as Any CPU.
Make sure that WranglerDataStructures.dll doesn't depend on other libraries that you are not referencing from F#. Either add the references in F#, or remove them from WranglerDataStructures.dll.
If these steps don't yield success try using the fuslogview.exe tool http://msdn.microsoft.com/en-us/library/e74a18c4.aspx to see exactly what reference is not being loaded.

Generate Bare Definitions for a Project or Namespace (Visual Studio)

In developing an SDK for use within our product, we want to provide users (developers) a Visual Studio plugin, mainly to provide them Intellisense during their development and ensure their code compiles for them. To do this, we strip the contents of all of our SDK APIs and put them all in a separate project.
For example:
public IEnumerable<string> AvailableConnections(bool querySystem) {
var connections = ConnectionList();
if(querySystem)
connections = connections.Concat(SystemConnections());
... // Filter connections somehow
return connections;
}
public void WriteToStream(Stream strFrom, Stream strTo) {
byte[] buffer = new byte[32 * 1024]; // 32 KiB
int len;
while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
Becomes:
public IEnumerable<string> AvailableConnections(bool querySystem) { return null; }
public void WriteToStream(Stream strFrom, Stream strTo) { }
My question: Does a tool exist to automate this, whether for a particular project or particular namespace? Ideally, it would intake a project or namespace and output all of the public classes/functions replacing their definitions with a simple return of the return type's default value. Visual Studio seems to do almost this when you view a class from which you don't have the source (e.g., you'll see IEnumerable<T> [from metadata]).
It sounds like you want to provide interfaces to your API.
You can build this into your project and essentially you will always have an assembly that shows all the public members without containing your implementation code.
Create a project that contains only the API, and reference that from your main project so that your concrete code (your implementation) implements the interfaces.
The API assembly would contain mostly interfaces and perhaps some abstract classes an helper, which you could share with developers.
Taking your example, you would have an interface like
public interface IMySdkThing
{
IEnumerable<string> AvailableConnections(bool querySystem);
void WriteToStream(Stream strFrom, Stream strTo);
}
Your implementation would be declared like:
public class MySdkThing : IMySdkThing
{
// all the code you showed, just as it is
}
All that said, it isn't clear how this will be useful to the developer. He or she will need a dll with some actual, executable code in it to use your library. Intellisense and compile-time checking come for free; you don't have to do anything special.

creating and using DLLs in visual studio c#

I have created my first dll using c# and visual studio 2010. I am trying to use it in a program. The dll is in the program directory but visual studio will not allow using myDLL stating that it could not be found. I have also tried adding it as a reference in the solution explorer. What more do I need to do?
Here is one of the files from my class.
namespace nbt
{
class TAG_Long
{
private string name;
private long payload;
public TAG_Long(FileStream f)
{
name = NameTag.SetTagName(f);
byte[] buffer = new byte[(int)dataBytes.TYPE_LONG];
f.Read(buffer, 0, (int)dataBytes.TYPE_LONG);
Array.Reverse(buffer);
payload = BitConverter.ToInt64(buffer, 0);
}
}
}
Try putting your class in a namespace

Resources