I am trying to implement Supersockets - https://supersocket.codeplex.com/ for a project i am working on. I have the a server that uses configuration to run.
In my project
I have referenced:
SuperSocket.Common,
SuperSocket.SocketBase,
SuperSocket.SocketEngine
I added the following config section:
<configSections>
<section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="ServiceName" value="SomeService" />
</appSettings>
<superSocket logFactory="ConsoleLogFactory"
disablePerformanceDataCollector="true"
maxWorkingThreads="500"
maxCompletionPortThreads="500"
minWorkingThreads="5"
minCompletionPortThreads="5">
<servers>
<server name="SomeService"
serverType="SomeService.Server.SomeService, SomeService"
ip="192.168.1.107"
port="4096"
disableSessionSnapshot="true"
clearIdleSession="false"
maxConnectionNumber="10"
sendWelcome="false">
</server>
</servers>
<logFactories>
<add name="ConsoleLogFactory"
type="SuperSocket.SocketBase.Logging.ConsoleLogFactory, SuperSocket.SocketBase" />
</logFactories>
</superSocket>
I also created the server and session class as follows:
namespace SomeService.Server
{
class SomeService: AppServer<SomeServiceSession>
{
protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
{
return base.Setup(rootConfig, config);
}
protected override void OnStartup()
{
base.OnStarted();
}
protected override void OnStopped()
{
base.OnStopped();
}
}
}
namespace SomeService.Server
{
class SomeServiceSession : AppSession<SomeServiceSession>
{
protected override void OnSessionStarted()
{
// this.Send("Welcome to SuperSocket Telnet Server");
}
protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
{
this.Send("Unknow request");
}
protected override void HandleException(Exception e)
{
this.Send("Application error: {0}", e.Message);
}
protected override void OnSessionClosed(CloseReason reason)
{
//add you logics which will be executed after the session is closed
base.OnSessionClosed(reason);
}
}
}
At this point the Server runs and it listens on a port as intended. Here is a wireshark representation of what i would want to do With SuperSocket http://imgur.com/rxKJbOD.
If you see on the request reply one chuck of the data :
.MSH|^~\&|MRI|ABC|||201403251406||QRY|173883426|P|2.1
QRD|201403251406|R|I|xxxxx|||25^RD|AB851656^|MPI
QRF|UPI||||
.
is from the client and
.MSH|^~\&|MRI|ABC|||201403251406||QRY|173883426|P|2.1
QRD|201403251406|R|I|xxxx|||25^RD|AB851656^|MPI
QRF|UPI||||
MSA|AA|173883426
.
is from the server. the response returned varies depending on the request and what is created after the business logic executes (but it is always going to be the same format- HL7 en(dot)wikipedia(dot)org/wiki/Health_Level_7 ). HL7 follows MLLP messaging format where each message begins with a Start Block code (0x0B) and each segment within the message is terminated with a Carriage Return code (0x0D) and each message is terminated by an End Block code (0x1C) followed by a Carriage Return code (0x0D). Once i get the request i have a business logic class that parses out the values, calls a web service gets the data and constructs a the tcp reply. What i would like to know is where in SuperSocket can i have a method or event listener to read the buffer and do my business logic and return the response for the same session. I know that there are concepts like filters and commands in SuperSocket but i haven't been able to figure them out. Any help is greatly appreciated. Let me know if you need additional detail.
Related
I want to host a WCF Rest Service with multiple contracts via mono each implemented in a separate partial class. I read many posts on similar issues, yet there was no solution for mono. I incorporated or at least tested all suggestions I could find and by now my code looks a lot like other solutions, yet does not work.
The application runs successfully on my local machine but throws an error once I deploy it via mono.
Service 'MyWebServiceEndpoint' implements multiple ServiceContract types, and no endpoints are defined in the configuration file.
Here is one of the endpoints with the contract. All the others are very much like this one. They all are a partial class MyWebServiceEndpoint implementing another contract.
namespace MyServer.MyEndPoints {
public partial class MyWebServiceEndpoint : INotificationEndpoint {
public string GetNotifications(int limit) {
// Do stuff
}
}
[ServiceContract]
public interface INotificationEndpoint {
[OperationContract]
[WebGet]
string GetNotifications(int limit);
}
}
My App.config looks like this. I removed the IP and port, as they are the server address.
<system.serviceModel>
<services>
<service name="MyServer.MyEndPoints.MyWebServiceEndpoint" behaviorConfiguration="WebService.EndPoint">
<host>
<baseAddresses>
<add baseAddress="http://ip:port>"/>
</baseAddresses>
</host>
<endpoint address="/message"
binding="webHttpBinding"
contract="MyServer.MyEndPoints.IMessageEndpoint"
behaviorConfiguration="WebBehavior"/>
<endpoint address="/music"
binding="webHttpBinding"
contract="MyServer.MyEndPoints.IMusicEndpoint"
behaviorConfiguration="WebBehavior"/>
<endpoint address="/notification"
binding="webHttpBinding"
contract="MyServer.MyEndPoints.INotificationEndpoint"
behaviorConfiguration="WebBehavior"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WebService.EndPoint">
<serviceMetadata httpGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
I open the service in C# like this.
WebServiceHost = new WebServiceHost(typeof(MyWebServiceEndpoint));
WebServiceHost.Open();
The Error message I receive on mono is:
Unhandled Exception:
System.InvalidOperationException: Service 'MyWebServiceEndpoint' implements multiple ServiceContract
types, and no endpoints are defined in the configuration file. WebServiceHost can set up default
endpoints, but only if the service implements only a single ServiceContract. Either change the
service to only implement a single ServiceContract, or else define endpoints for the service
explicitly in the configuration file. When more than one contract is implemented, must add base
address endpoint manually
I hope you have some hints or someone knows how to solve the issue. Thank you already for reading up to here.
I am not familiar with Mono, Does the Mono support Webconfig file? I advise you to add the service endpoint programmatically.
class Program
{
/// <param name="args"></param>
static void Main(string[] args)
{
WebHttpBinding binding = new WebHttpBinding();
Uri uri = new Uri("http://localhost:21011");
using (WebServiceHost sh = new WebServiceHost(typeof(TestService),uri))
{
sh.AddServiceEndpoint(typeof(ITestService), binding, "service1");
sh.AddServiceEndpoint(typeof(IService), binding, "service2");
ServiceMetadataBehavior smb;
smb = sh.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
{
smb = new ServiceMetadataBehavior()
{
HttpGetEnabled = true
};
sh.Description.Behaviors.Add(smb);
}
sh.Opened += delegate
{
Console.WriteLine("service is ready");
};
sh.Closed += delegate
{
Console.WriteLine("service is closed");
};
sh.Open();
Console.ReadLine();
sh.Close();
}
}
}
[ServiceContract]
public interface ITestService
{
[OperationContract]
[WebGet]
string GetData(int id);
}
[ServiceContract]
public interface IService
{
[OperationContract]
[WebGet]
string Test();
}
public class TestService : ITestService,IService
{
public string GetData(int id)
{
return $"{id},";
}
public string Test()
{
return "Hello " + DateTime.Now.ToString();
}
}
Result.
According to the official documentation, we had better not use Partial class.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/multiple-contracts
Besides, we could consider launching multiple service host for every service implemented class.
Feel free to let me know if the problem still exists.
I have an Azure bot service which runs perfectly when tested on webchat.
Now I tried to open a websocket and test the bot.
I first send a POST request (with all required headers) to https://directline.botframework.com/v3/directline/conversations
I get a response with
{
"conversationId": "7FY18sO6FCT9OVi0pW7WBY",
"token": "my_token_here",
"expires_in": 1800,
"streamUrl":
"wss://directline.botframework.com/v3/directline/conversations/7FY18sO6FCT9OVi0pW7WBY/stream?watermark=-&t=token_value_here",
"referenceGrammarId": "c1c290dd-f896-5857-b328-cdc10298e440"
}
Now I try to use the streamUrl to send/receive data using web socket.
I got an error: Undefined
I tried to test the streamUrl on different online websocket testing tool. I still got the undefined error.
How can I test whether there is a problem in the streamUrl?
How can I test the web socket?
Firstly, as Eric Dahlvang mentioned, it enables us to receive activities via WebSocket stream, but not send activities.
Besides, I do a test with the following steps and sample, the activities can be received as expected via WebSocket stream, you can refer to it.
Step1: make a request to start a conversation
Step2: start client app (a console application) to wait for receiving acitivities
class Program
{
private static string botId = "fehanbasicbot";
static void Main(string[] args)
{
var url = Console.ReadLine();
StartReceivingActivities(url).Wait();
Console.ReadLine();
}
private static async Task StartReceivingActivities(string url)
{
var webSocketClient = new WebSocket(url);
webSocketClient.OnMessage += WebSocketClient_OnMessage;
webSocketClient.Connect();
}
private static void WebSocketClient_OnMessage(object sender, MessageEventArgs e)
{
// Occasionally, the Direct Line service sends an empty message as a liveness ping. Ignore these messages.
if (string.IsNullOrWhiteSpace(e.Data))
{
return;
}
var activitySet = JsonConvert.DeserializeObject<ActivitySet>(e.Data);
var activities = from x in activitySet.Activities
where x.From.Id == botId
select x;
foreach (Activity activity in activities)
{
Console.WriteLine(activity.Text);
}
}
}
packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bot.Connector.DirectLine" version="3.0.2" targetFramework="net461" />
<package id="Microsoft.Rest.ClientRuntime" version="2.3.2" targetFramework="net461" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net461" />
<package id="WebSocketSharp" version="1.0.3-rc11" targetFramework="net461" />
</packages>
Step3: make a request to send an activity to the bot
Step4: check the console app output, I can find the activities are received
I created a simple rest service with routing enabled. The routing is properly working when i run it locally i.e using asp.net development server. But when I deploy the application in IIS (IIS 7.5) then it and try to access the method in the service i get the error HTTP 404.0 Not found. Here is my code :
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class HelloWorldService
{
[WebGet(UriTemplate = "Date")]
public DateTime Date()
{
return System.DateTime.Now;
}
}
Global.asax:
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
RouteTable.Routes.Add(new ServiceRoute("ServiceData", new WebServiceHostFactory(), typeof(HelloWorldService)));
}
Web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
I also Enabled HTTP Redirection Feature under
Windows Features -> Internet Information Services -> Word Wide Web services -> Common HTTP Features
I also tried Adding handlers like
<handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</handlers>
Also i have tried all the other solutions that were suggested on the web but nothing works. Thanks in advance for any help.
Something is wrong with your RegisterRoutes(). It should be:
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("HelloWorldService", new WebServiceHostFactory(), typeof(HelloWorldService)));
}
I have a (Smart)GWT application, that uses Spring on the server-side, and logs its stuff there via log4j. This works (deploying on tomcat6/ubuntu 10.04 LTS).
On the client-side I use the gwt-log remote logging library, configured properly. When running debug mode, I see the gwt-logs in the Eclipse 'Development Mode' pane. When deployed however, I don't see the gwt-log logs. I have configured things as follows:
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
...
<appender name="FILE_LOG2" class="org.apache.log4j.FileAppender">
<param name="File" value="${PuzzelVandaag-instance-root}WEB-INF/logs/Sytematic.log" />
<param name="Append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="--- %d [%.4t] %-5p %c{1} - %m%n"/>
</layout>
</appender>
...
<!-- this one works, normal server-side code -->
<category name="com.isomorphic">
<priority value="DEBUG" />
<appender-ref ref="FILE_LOG2" />
</category>
<!-- currently I use this to configure gwt-log stuff. Is this the right way? -->
<category name="gwt-log">
<level value="DEBUG" />
<appender-ref ref="FILE_LOG2"/>
</category>
The server-side package logging works, but I have troubles with the client-side. I am fairly sure the remote logging servlet works, as I don't see any errors on this. I have it configured as follows, in web.xml:
<servlet>
<servlet-name>gwt-log-remote-logger-servlet</servlet-name>
<servlet-class>com.allen_sauer.gwt.log.server.RemoteLoggerServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gwt-log-remote-logger-servlet</servlet-name>
<url-pattern>/[modulename]/gwt-log</url-pattern>
</servlet-mapping>
When I log stuff, I do a call like Log.debug("some msg"), whilst importing com.allen_sauer.gwt.log.client.Log.
All-in-all I think I followed the correct approach. I also run hosted mode with the -Dlog4j.debug parameter, and this is what it tells me:
log4j: Retreiving an instance of org.apache.log4j.Logger.
log4j: Setting [gwt-log] additivity to [true].
log4j: Level value for gwt-log is [DEBUG].
log4j: gwt-log level set to DEBUG
log4j: Adding appender named [STDOUT] to category [gwt-log].
log4j: Adding appender named [SmartClientLog] to category [gwt-log].
log4j: Adding appender named [FILE_LOG2] to category [gwt-log].
For completion, here is the relevant part of .gwt.xml:
<inherits name="com.allen_sauer.gwt.log.gwt-log-DEBUG"/>
<set-property name="log_DivLogger" value="DISABLED"/>
<!-- In gwt-log-3.0.3 or later -->
<inherits name="com.allen_sauer.gwt.log.gwt-log-RemoteLogger"/>
Am I missing something obvious? I am a log4j newbie... Any help would be greatly appreciated!
If you take a look at the com.google.gwt.logging.server.RemoteLoggingServiceImpl code you will see that it is using java.util.logging.Logger to perform it's logging.
You are using Log4j.
There are two options for getting your logs to appear in Log4j.
Implement your own RemoteLoggingService
Use slf4j to "bridge" java.util.logging with log4j logging
Option 1 is not too hard.
I have below the class I created for this. Remember to point your web.xml to this new class.
import java.util.logging.LogRecord;
import com.google.gwt.logging.shared.RemoteLoggingService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.logging.Level;
import org.springframework.stereotype.Component;
public class MyRemoteLoggingServlet extends RemoteServiceServlet implements RemoteLoggingService {
private final MyLogger logger = MyLoggerFactory.getLogger(getClass());
#Override
public String logOnServer(LogRecord record) {
Level level = record.getLevel();
String message = record.getMessage();
if (Level.INFO.equals(level)) {
logger.info(message);
} else if (Level.SEVERE.equals(level)) {
logger.error(message);
} else if (Level.WARNING.equals(level)) {
logger.warn(message);
} else if (Level.FINE.equals(level)) {
logger.debug(message);
}
return null;
}
}
Option 2
In this option you use SLF4J for your logging and configure a bridge that will redirect the java.util.logging.Logger to Log4j.
I havent implemented this method myself, but you can read about it here:
JUL to SLF4J Bridge
I took this approach, works for me.
public class UILogging extends RemoteServiceServlet implements
RemoteLoggingService {
private static final String SYMBOL_MAPS = "symbolMaps";
private static StackTraceDeobfuscator deobfuscator = null;
private static Logger logger = Logger.getLogger(UILogging.class);
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
setSymbolMapsDirectory(config.getInitParameter(SYMBOL_MAPS));
}
/**
* Logs a Log Record which has been serialized using GWT RPC on the server.
*
* #return either an error message, or null if logging is successful.
*/
public final String logOnServer(LogRecord lr) {
String strongName = getPermutationStrongName();
try {
if (deobfuscator != null) {
lr = deobfuscator.deobfuscateLogRecord(lr, strongName);
}
if (lr.getLevel().equals(Level.SEVERE)) {
logger.error(lr.getMessage(),lr.getThrown());
} else if (lr.getLevel().equals(Level.INFO)) {
logger.info(lr.getMessage(),lr.getThrown());
} else if (lr.getLevel().equals(Level.WARNING)) {
logger.warn(lr.getMessage(),lr.getThrown());
} else if (lr.getLevel().equals(Level.FINE)) {
logger.debug(lr.getMessage(),lr.getThrown());
} else if (lr.getLevel().equals(Level.ALL)) {
logger.trace(lr.getMessage(),lr.getThrown());
}
} catch (Exception e) {
logger.error("Remote logging failed", e);
return "Remote logging failed, check stack trace for details.";
}
return null;
}
/**
* By default, this service does not do any deobfuscation. In order to do
* server side deobfuscation, you must copy the symbolMaps files to a
* directory visible to the server and set the directory using this method.
*
* #param symbolMapsDir
*/
public void setSymbolMapsDirectory(String symbolMapsDir) {
if (deobfuscator == null) {
deobfuscator = new StackTraceDeobfuscator(symbolMapsDir);
} else {
deobfuscator.setSymbolMapsDirectory(symbolMapsDir);
}
}
}
I am trying to run a method in C# Interactive that return some data from local db using Entity Framework. But it return an error saying that the connection string named 'InteractiveConsoleDBEntities' could be found in the application config file.
I am using data base first.
I use the option "Initialize Interactive with project" to start with C# Interactive.
Here is the details...
Commands in Interactive Console
#r "C:\Users\Path\InteractiveConsole\packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.ComponentModel.DataAnnotations.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Core.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Data.Entity.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Runtime.Serialization.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Security.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Xml.Linq.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Data.DataSetExtensions.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\Microsoft.CSharp.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Data.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Net.Http.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Xml.dll"
#r "InteractiveConsole.exe"
using InteractiveConsole;
using InteractiveConsole.Model;
using InteractiveConsole.DAL;
var context = new InteractiveConsoleDBEntities();
context.Employees.ToList();
Then I get the error
No connection string named 'InteractiveConsoleDBEntities' could be found in the application config file.
+ System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel()
+ System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
+ System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(System.Type)
+ InternalSet<TEntity>.Initialize()
+ InternalSet<TEntity>.Include(string)
+ DbQuery<TResult>.Include(string)
+ System.Data.Entity.DbExtensions.Include<T>(IQueryable<T>, string)
+ System.Data.Entity.DbExtensions.Include<T, TProperty>(IQueryable<T>, Expression<Func<T, TProperty>>)
+ InteractiveConsole.DAL.EmployeeDAL.GetEmployeeList()
The App.config file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<connectionStrings>
<add name="InteractiveConsoleDBEntities" connectionString="metadata=res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\DB\InteractiveConsoleDB.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
The DbContext
namespace InteractiveConsole.Model
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class InteractiveConsoleDBEntities : DbContext
{
public InteractiveConsoleDBEntities()
: base("name=InteractiveConsoleDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Person> People { get; set; }
}
}
The class with method
using System.Data.Entity;
namespace InteractiveConsole.DAL
{
public class EmployeeDAL
{
public static List<Employee> GetEmployeeList()
{
using (var context = new InteractiveConsoleDBEntities())
{
return context.Employees.Include(x => x.Person).ToList();
}
}
}
}
The same project in Immediate Window works fine
InteractiveConsole.DAL.EmployeeDAL.GetEmployeeList()
Count = 2
[0]: {System.Data.Entity.DynamicProxies.Employee_0D99EB301BB74EDFF2203163D6E8A936C70F24995F1639BF58D81DCCA671DEC0}
[1]: {System.Data.Entity.DynamicProxies.Employee_0D99EB301BB74EDFF2203163D6E8A936C70F24995F1639BF58D81DCCA671DEC0}
Hope some one know what I doing wrong and can help me.
Thanks a lot
Struggled with this one for a while before I finally got it working.
Create a new partial class (for example named YourEntities.cs) with a new overload for your constructor that takes a connection string parameter (don't modify your existing class as it will be overwritten whenever you re-model the database):
using System.Data.Entity;
namespace YourNamespace.Models
{
public partial class YourEntities : DbContext
{
public YourEntities(string connectionString)
: base(connectionString)
{
}
}
}
Then, build your project, right click it and click "Initialize Interactive with Project". Open your web.config / app.config and copy the connection string to your clipboard.
In the interactive window, paste this replacing ConnStringHere with your connection string but don't hit enter:
var db = new YourNamespace.Models.YourEntities("ConnStringHere");
After you paste, replace " in the connection string with \" , go to the end of the line in C# interactive and hit enter.
Then you should be able to use db in your C# Interactive window it as if it were in your app:
Print(db.Employees.Count());
I realize this is old, but I found a way to make this work without changing my code, or creating any proxies or other work-around code. I was able to make this work by editing the config file for the interactive window, itself. See my answer in this post:
Project can't find my EF connection string in C# Interactive
You may have to add other config data, as well, if your app relies on it. Just adding the connection string was enough, for me.