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.
Related
Is it possible to read nuget.config file and packages sources inside with using Nuget.visualStudio,nuget.core or nuget.clients dll.I can parse xml but is there any outofthebox logic in nuget.dlls
Yes! You need to consume the NuGet.Configuration package available at https://www.nuget.org/packages/NuGet.Configuration/4.6.2.
Then you can use the following code -
using NuGet.Configuration;
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
// basic implementation of nuget.config in code
var setting = Settings.LoadSpecificSettings(#"f:\root", "nuget.config");
// get sources
var packageSourceProvider = new PackageSourceProvider(setting);
var sources = packageSourceProvider.LoadPackageSources();
foreach(var source in sources)
{
Console.WriteLine($"{source.Name}: {source.SourceUri}");
}
}
}
}
This will generate the following output -
NuGet.org: https://api.nuget.org/v3/index.json
Sample config file used (lets say at path f:\root\nuget.config)-
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="NuGet.org" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>
I have an application which has three layers.I am using EntityFramework 6.1 and code first migrations using existing database.The three layers are given below:
1.Presententation Layer:ConceptuCodeFirstMigrationDemo
Simply a Console Application for simplicity
Data Layer Consists of Context and Initializer.The codes are given below:
namespace ConceptuCodeFirstMigrationDemo.Data.DataContext
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using ConceptuCodeFirstMigrationDemo.Domain;
public partial class ConceptuContext : DbContext,IDisposable
{
public ConceptuContext()
: base("name=ConceptuContext")
{
}
public virtual DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.WithRequired(e => e.User)
.HasForeignKey(e => e.CreatedBy)
.WillCascadeOnDelete(false);
}
}
}
ConceptuInitializer.Cs
namespace ConceptuCodeFirstMigrationDemo.Data.DataContext
{
public class ConceptuInitializer: System.Data.Entity.CreateDatabaseIfNotExists<ConceptuContext>
{
}
}
Appconfig:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- 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>
<entityFramework>
<contexts>
<context type="ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext, ConceptuCodeFirstMigrationDemo.Data">
<databaseInitializer type="ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuInitializer, ConceptuCodeFirstMigrationDemo.Data" />
</context>
</contexts>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="ConceptuContext" connectionString="data source=AMITABHA-PC;initial catalog=Conceptu;user id=sa;password=lovediya;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Domain Layer: Consists of entity class for example user
After writing a new class when I try to enable migrations using Enable-Migrations
showing
No context type was found in the assembly 'ConceptuCodeFirstMigrationDemo'.
After I tried the following command:
Enable-Migrations -ContextTypeName ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext
this shows following error
The context type 'ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext' was not found in the assembly 'ConceptuCodeFirstMigrationDemo'.
After I tried the following command
Enable-Migrations ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext
It shows the following error
Enable-Migrations : A positional parameter cannot be found that accepts argument 'ConceptuCodeFirstMigrationDemo.Data.DataContext.Concept
uContext'.
At line:1 char:18
+ Enable-Migrations <<<< ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext
+ CategoryInfo : InvalidArgument: (:) [Enable-Migrations], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Enable-Migrations
Try this.
Enable-Migrations -ContextTypeName ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext -ProjectName ConceptuCodeFirstMigrationDemo
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.
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'd like to use PowerShell as part of our automated build process to update an App.config file while deploying into our test environment. How can I do this?
Given this sample App.config: C:\Sample\App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConnectionString"
connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"/>
</connectionStrings>
</configuration>
The following script, C:\Sample\Script.ps1, will read and write a setting:
# get the directory of this script file
$currentDirectory = [IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path)
# get the full path and file name of the App.config file in the same directory as this script
$appConfigFile = [IO.Path]::Combine($currentDirectory, 'App.config')
# initialize the xml object
$appConfig = New-Object XML
# load the config file as an xml object
$appConfig.Load($appConfigFile)
# iterate over the settings
foreach($connectionString in $appConfig.configuration.connectionStrings.add)
{
# write the name to the console
'name: ' + $connectionString.name
# write the connection string to the console
'connectionString: ' + $connectionString.connectionString
# change the connection string
$connectionString.connectionString = 'Data Source=(local);Initial Catalog=MyDB;Integrated Security=True'
}
# save the updated config file
$appConfig.Save($appConfigFile)
Execute the script:
PS C:\Sample> .\Script.ps1
Output:
name: dbConnectionString
connectionString: Data Source=(local);Initial Catalog=Northwind;Integrated Security=True
Updated C:\Sample\App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="dbConnectionString"
connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" />
</connectionStrings>
</configuration>
The code can be much more shorter (based on Robin's app.config):
$appConfig = [xml](cat D:\temp\App.config)
$appConfig.configuration.connectionStrings.add | foreach {
$_.connectionString = "your connection string"
}
$appConfig.Save("D:\temp\App.config")