Assembly reference missing in wcf service application - c#

I am creating a Web application using WCF service.
Steps i followed is,
1) Created a new WCF Service Application.
2)Added a new WCF Service.
3) Created a Class Library.
4)Added a new class where i am having these codes mentioned below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace ClassLibrary1
{
public interface IUSerDetails
{
[OperationContract]
string InsertUserDetails(UserDetails user);
}
[DataContract]
public class UserDetails
{
string username = string.Empty;
string password = string.Empty;
string country = string.Empty;
string email = string.Empty;
[DataMember]
public string UserName
{
get { return username; }
set { username = value; }
}
[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
[DataMember]
public string Country
{
get { return country; }
set { country = value; }
}
[DataMember]
public string Email
{
get { return email; }
set { email = value; }
}
}
}
Now in Ln 13 when i do mousehover on [OperationContract]. It Gives an error. Are you missing a using directive or an assembly reference.
So i thought i missed the namespace
i added
using system.ServiceModel; , but again its showing the same error in both the lines. What is missing out there?

I was using Visual Studio for Mac to create a new Console project in .NET Framework 4.7.
Oddly it was quite happy with the [ServiceContract] attributes coming from System.ServiceModel but was complaining about the [OperationContract] attributes:
Program.cs(10,10): Error CS0246: The type or namespace name 'OperationContactAttribute' could not be found (are you missing a using directive or an assembly reference?) (CS0246)
Program.cs(10,10): Error CS0246: The type or namespace name 'OperationContact' could not be found (are you missing a using directive or an assembly reference?) (CS0246)
After checking the OperationContractAttribute Class documentation I discovered that the System.ServiceModel.Primitives assembly was required. For some reason the System.ServiceModel.Primitives assembly is not available in the Packages and .NET Assembly tabs via Project References.
I deleted all assemblies from Project References and fixed the above error with NuGet, i.e.:
Install-Package System.ServiceModel.Primitives
In addition to adding System.ServiceModel.Primitives to the Project References it also re-added:
mscorlib
System
System.IdentityModel
System.Runetime.Serialization
System.ServiceModel
System.Xml
Now I can re-add the other assemblies I need to continue. Hope this helps.

as per link https://social.msdn.microsoft.com/Forums/vstudio/en-US/96ffb6d7-8737-4c4d-8512-58967d0b69cd/wcf-on-godaddy-compiler-doesnt-recognize-operationcontract?forum=wcf , you need to make two changes. First, add the following line to the httpmodules section of the web.config file:
<httpModules>
<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</httpModules>
Second, add the following lines to the assemblies section of the web.config file:
<assemblies>
<add assembly="System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<add assembly="System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>

Write [ServiceContract] above the Line "interface IUSerDetails"

Related

Blazor namespace Interop does not extist in the namespace

Where do I find the assembly reference and how can I add it?
Error Description:
CS0234 The type or namespace name 'Interop' does not exist in the namespace 'Microsoft.AspNetCore.Blazor.Browser' (are you missing an assembly reference?)
CS0103 The name 'RegisteredFunction' does not exist in the current context Phoneword.Client
I have a small Blazor project which I would like to run again after some time. But it seems I've deleteted the reference or something else is broken.
Edit I:
Blazor: 0.5.1
Target framework: .NET Standart 2.0
'RegisteredFunction' does not exist anymore.
This is how you define a function in a JavaScript file:
window.exampleJsFunctions = {
showPrompt: function (message) {
return prompt(message, 'Type anything here');
}
};
And this is how you call the function from your Blazor code:
using Microsoft.JSInterop;
public class ExampleJsInterop
{
public static Task<string> Prompt(string message)
{
// Implemented in exampleJsInterop.js
return JSRuntime.InvokeAsync<string>(
"exampleJsFunctions.showPrompt",
message);
}
}

How do I add custom ConfigurationSection to Assembly?

I've spent a few weeks trying to figure this out, this is a duplicate of a question I asked previously but did not get a response to, so I am refining the question here.
I've created a custom class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Configuration;
namespace mssql_gui
{
public class TestConfigSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
public TestConfigInstanceCollection Instances
{
get { return (TestConfigInstanceCollection)this[""]; }
set { this[""] = value; }
}
}
public class TestConfigInstanceCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new TestConfigInstanceElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((TestConfigInstanceElement)element).Key;
}
}
public class TestConfigInstanceElement : ConfigurationElement
{
[ConfigurationProperty("key", IsKey = true, IsRequired = true)]
public string Key
{
get { return (string)base["key"]; }
set { base["key"] = value; }
}
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)base["value"]; }
set { base["value"] = value; }
}
}
}
I've implemented it:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="testSection" type="mssql_gui.TestConfigSection"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
<appSettings>
<add key="Data Source" value="localhost\SQLEXPRESS"/>
<add key="Initial Catalog" value="(empty)"/>
<add key="Integrated Security" value="SSPI"/>
</appSettings>
<testSection>
<add key ="testKey" value="tesValue"/>
</testSection>
</configuration>
and I have tried to access it, I am getting:
An error occurred creating the configuration section handler for testSection: Could not load type 'mssql_gui.TestConfigSection' from assembly 'System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
I understand that in the type, I should be declare an assembly dll, but I'm confused about that...because in the official instructions by MS, it says to create a new class for the handler:
Create a public class that inherits from the
System.Configuration.ConfigurationSection class.
Add code to define the section's attributes and elements.
Adding the class (at least through the visual studio interface) creates a .cs file, not a .dll assembly file, so how to I add that custom class to an assembly file in order to reference it in the <configSections> part of app.config?
If I understand correctly, you have problem with resolving what actually your Assembly is, since you are only creating .cs files that determine types that this file hold.
Assembly (in maybe not so accurate shorcut) is just the project you have in your solution. It will get compiled into its seperate assembly - the .dll you mentioned - later on.
When you add class to any .cs file in given project, on compile it will be included in project's assembly.
By default, if you won't provide assembly for configSection where its corresponding type should be found, App.config defaults to System.Configuration assembly - that's where you get your error from, since you've declared your section in your own assembly (== project).
Right click in Visual Studio on your project that holds App.config file and choose Properties to check its Assembly name:
Then add this name to your App.config section declaration. In my example its ConsoleApp1, so I will add it to configuration accordingly:
<configSections>
<section name="testSection" type="mssql_gui.TestConfigSection, ConsoleApp1"/>
</configSections>
Ensure that the type attribute of the section element matches the
manifest of the assembly (ensure that you specify both the correct
namespace and type name).
You need to add the name of the assembly (where the type relies) to the type attribute:
You'll get the name of the assembly from the AssemblyInfo.cs within the project where TestConfigSection class is defined.
<section name="testSection" type="mssql_gui.TestConfigSection, ASSEMBLYNAME"/>
Example asuming your assembly names mssql_gui
<section name="testSection" type="mssql_gui.TestConfigSection, mssql_gui"/>
You read it like this:
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
TestConfigSection mySec = (TestConfigSection)config.Sections["testSection"];
See more details at MSDN
How to: Create Custom Configuration Sections Using ConfigurationSection

System.IO.FileNotFoundException: Could not load file or assembly 'System.Web.DataVisualization MEF MVC

I am creating a website which should be able to take in multiple modules and compose those modules to a main project. After programming the bootstrapper and custom View engine to make it able to find Views in the module.dll.
After compiling a test module for testing, I am getting a weird error where it says it cannot load System.Web.DataVisualization for some reason. I have also noticed that the Controller from the Module dll gets loaded properly, I can see it in the debug but this error keeps killing a thread and throws the error.
This is the code I have for Bootstrapper.cs that handles the loading/composing of the dlls.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
public class Bootstrapper
{
private static CompositionContainer CompositionContainer;
private static bool IsLoaded = false;
public static void Compose(List<string> pluginFolders)
{
if (IsLoaded) return;
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")));
foreach (var plugin in pluginFolders)
{
var directoryCatalog = new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", plugin));
catalog.Catalogs.Add(directoryCatalog);
}
CompositionContainer = new CompositionContainer(catalog);
CompositionContainer.ComposeParts();
IsLoaded = true;
}
public static T GetInstance<T>(string contractName = null)
{
var type = default(T);
if (CompositionContainer == null) return type;
if (!string.IsNullOrWhiteSpace(contractName))
type = CompositionContainer.GetExportedValue<T>(contractName);
else
type = CompositionContainer.GetExportedValue<T>();
return type;
}
}
And this is the error that gets thrown out when testing.
The solution for this was to unfortunately manually download the dll and add it to the reference, but the main edit was to Web.Config where I had to define the assembly to import System.Web.DataVisualization as such. <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

The type of namespace name could not be found (are you missing a using directive or an assembly reference?)

I have this class:
using System;
using System.Web.Mvc;
using System.Data;
using BLL;
namespace LicenseManager.Controllers
{
public class ValidationController : BaseController
{
public ActionResult Default()
{
return View("Default");
}
[HttpPost]
public JsonResult ClearInstallation(FormCollection form)
{
var jr = new JsonResult();
try
{
var licMgr = new BLL.LicManager();
licMgr.ClearInstall(form["regKey"], form["checkKey"]);
}
catch (Exception exc)
{
jr = Json(new { success = "false", error = exc.Message });
}
return jr;
}
}
}
When I try to rebuild or debug I receive the error: The type of namespace name 'BLL' could not be found (are you missing a using directive or an assembly reference?)
I can see that it is referenced:
The intellisense works, and I don't have any errors, until I try to rebuild or compile. I know it exists, and it finds it for intellisense purposes, so why won't it allow me to rebuild or compile?
I have tried:
cleaning the solution
rebuilding
clearing the reference and re-adding it
What else can I try?
UPDATE
If you get this error, make sure you read the output. It contained the solution for me.
I had a similar problem when the referenced project was using a different .net framework. Make sure the project you are building and the project you have referenced are using the same framework.
You can verify/change the framework in properties/application/target framework

Mono can't cast TypeA to TypeA

I'm creating a plugin framework with C#. The main requirements of the framework is to load, unload and update plugins at runtime.
To accomplish this I've been creating AppDomains and loading the plugin assemblies into the AppDomains.
Everything works fine on Microsoft .NET on windows but the plugins do not work on mono running on mac or linux.
When trying to start a plugin I get an exception like this:
Cannot cast argument 0 of type 'System.Func`1[[API.Network.NodeType, API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' to type 'System.Func`1[[API.Network.NodeType, API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
This is caused because each plugin has it's own copy of the API.dll assembly, and though the assembly is an identical copy, mono doesn't see the Types as being the same.
How can I get the plugin to load the API.dll from the main application's directory? Or, alternatively, how can I get mono to see the Types as being the same?
Well to find answer to your question I created a simple plugin system and tested it on mono 3.2.3 under the Windows successfully (unfortunately I can't make test on Linux now, maybe tomorrow). My code:
SDK.dll
using System;
namespace SDK
{
public interface IPlugin
{
void SomeMethod();
SomeSDKType GetSDKType();
}
}
using System;
using System.Collections.Generic;
namespace SDK
{
[Serializable]
public class StringEventArgs : EventArgs
{
public string Message { get; set; }
}
public class SomeSDKType : MarshalByRefObject
{
public event EventHandler<StringEventArgs> SDKEvent;
public Action SDKDelegate;
public void RiseSDKEvent(string message)
{
var handler = SDKEvent;
if (handler != null) SDKEvent(this, new StringEventArgs { Message = message });
}
public Dictionary<int, string> GetDictionary()
{
var dict = new Dictionary<int, string> ();
dict.Add(1, "One");
dict.Add(2, "Two");
return dict;
}
}
}
Plugin.dll
using System;
using SDK;
namespace Plugin
{
public class Plugin : MarshalByRefObject, IPlugin
{
public Plugin()
{
}
public void SomeMethod()
{
Console.WriteLine("SomeMethod");
}
public SomeSDKType GetSDKType()
{
var obj = new SomeSDKType();
obj.SDKDelegate = () => Console.WriteLine("Delegate called from {0}", AppDomain.CurrentDomain.FriendlyName);
return obj;
}
}
}
Hosting program
using System;
using System.Reflection;
using System.IO;
using SDK;
namespace AppDomains
{
class MainClass
{
public static void Main(string[] args)
{
var domain = AppDomain.CreateDomain("Plugin domain"); // Domain for plugins
domain.Load(typeof(IPlugin).Assembly.FullName); // Load assembly containing plugin interface to domain
var currentPath = Directory.GetCurrentDirectory();
var pluginPath = Path.Combine(currentPath, "Plugins");
var pluginFiles = Directory.GetFiles(pluginPath, "*.dll");
foreach (var pluginFile in pluginFiles) // Foreach dll in Plugins directory
{
var asm = Assembly.LoadFrom(pluginFile);
foreach (var exportedType in asm.GetExportedTypes())
{
if (!typeof(IPlugin).IsAssignableFrom(exportedType)) continue; // Check if exportedType implement IPlugin interface
domain.Load(asm.FullName); // If so load this dll into domain
var plugin = (IPlugin)domain.CreateInstanceAndUnwrap(asm.FullName, exportedType.FullName); // Create plugin instance
plugin.SomeMethod(); // Call plugins methods
var obj = plugin.GetSDKType();
obj.SDKDelegate();
var dict = obj.GetDictionary();
foreach (var pair in dict)
{
Console.WriteLine("{0} - {1}", pair.Key, pair.Value);
}
obj.SDKEvent += obj_SDKEvent;
obj.RiseSDKEvent(string.Format("Argument from domain {0}", AppDomain.CurrentDomain.FriendlyName));
}
}
Console.ReadLine();
}
static void obj_SDKEvent(object sender, StringEventArgs e)
{
Console.WriteLine("Received event in {0}", AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine(e.Message);
}
}
}
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="Plugins"/>
</assemblyBinding>
</runtime>
</configuration>
Some explanation to code. I created SDK dll with plugin interface. All plugins and host app must reference to it. Plugins must be provided without SDK dll because host app already contains it. They puts into the Plugins directory in the host application directory (ie if app path = c:\MyApp the plugins are in c:\MyApp\Plugins) so to provide CLR (or mono) opportunity to find plugin assemplies I also created App.config file with probing element.
Hope this helps.

Categories