Not getting connection string value in wcf service method - c#

I am having 1 class library named as AuxiliaryLib which contains app settings like below:
<appSettings>
<add key="connectionstring" value="Data Source=My-Pc;Initial Catalog=Db1;User ID=StackOverflow;Password=123456"></add>
</appSettings>
Now, in this class library I have 1 class file which return connection string like below:
public static string ReturnConnectionString()
{
return System.Configuration.ConfigurationManager.AppSettings["connectionstring"];
}
I have 1 wcf project in which i have given reference of above class library i.e AuxiliaryLib and calling above connection string method but I am getting null.
Public void MyMethod()
{
var connectionRepo = new ConnectionRepo();
string str = ConnectionRepo.ReturnConnectionString(); //getting null
}
I have web.config in wcf project where I have added connection string but still getting null:
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="connectionstring" value="Data Source=My-Pc;Initial Catalog=Db1;User ID=StackOverflow;Password=123456"></add>
</appSettings>
<!--<connectionStrings>
<add name="connectionstring" connectionString="Data Source=My-Pc;Initial Catalog=Db1;User ID=StackOverflow;Password=123456"></add>
</connectionStrings>-->
Public void MyMethod(string regionId)
{
string str = ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString; // null
string str = System.Configuration.ConfigurationManager.AppSettings["connectionstring"];// null
}
Note : MyMethod is running on threadpool:
ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod), new object[] { regionId });

Did you try....
using System.Web.Configuration;
WebConfigurationManager.AppSettings["connectionstring"]

Related

Changing a path for logger using Form application and implementing it to Service with C#

I am working on a File Watcher service which has a form application in it too (2 different projects in same solution). So I am getting a path for where to save the log with Forms application. Then I put that in my app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="location" value="C:\Users\user\Documents" />
<add key="logLocation" value="C:\Users\user\Documents" /> <!-- this is where it changes save it-->
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
And I have a Variables class where I define my variable.
using System.Configuration;
namespace FileWatchingService
{
public static class Variables
{
public static string FilePath { get; set; } = ConfigurationManager.AppSettings.Get("location");
public static string LogPath { get; set; } = ConfigurationManager.AppSettings.Get("logLocation");
}
}
Then I am trying put my LogPath in here:
using System;
using System.IO;
namespace FileWatchingService
{
public static class Logger
{
public static void Log(string message)
{
try
{
string _message = String.Format("{0} {1}", message, Environment.NewLine);
//File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "logFile.log", _message);
File.AppendAllText(Variables.LogPath + "logFile.log", _message);
}
catch (Exception ex)
{
//Implement logging on next version
}
}
}
}
Problem is that my way does not work. What can I do to change my log files path?
Looking solely at the code, it seems you're missing a \ at the end of the LogPath value.
You could also do File.AppendAllText(Variables.LogPath + "\logFile.log", _message); or just define the LogPath itself, such as:
<appSettings>
<add key="location" value="C:\Users\user\Documents" />
<add key="logLocation" value="C:\Users\user\Documents\log.txt" /> <!-- the file itself -->
</appSettings>
Nevertheless, I would advise to just use a library for logging, instead of developing your own. Go with NLog or Serilog

set "Application.StartupPath" in may app.config connectionstring

in App.Config file :
<connectionStrings>
<add name="DB_PhonebookEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.;Initial Catalog=DB_Phonebook;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
in MyModel.Designer.cs file :
namespace SimplePhoneBook
{
public partial class DB_PhonebookEntities : ObjectContext
{
public DB_PhonebookEntities() : base("name=DB_PhonebookEntities", "DB_PhonebookEntities")
{
....
}
public DB_PhonebookEntities(string connectionString): base(connectionString, "DB_PhonebookEntities")
{
....
}
public DB_PhonebookEntities(EntityConnection connection) : base(connection, "DB_PhonebookEntities")
{
....
}
....
}
How can I set Application.StartupPath into my ConnectionString?
I want create "Model" from my database thais on the applicatin path(...\debug\bin\mydatabase.mdf)
and using entities in my model!
Append this to your connection string. This will point to WebApplication1\App_Data. So your mdf file should be in App_Data folder
AttachDBFilename=|DataDirectory|\aspnet-WebApplication1-20141203171438.mdf

EF connection String Error

My connection String in web.config file:
<connectionStrings>
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EFcodefirst-20131213155231;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EFcodefirst-20131213155231.mdf" />
</connectionStrings>
My context File
namespace EFcodefirst.Models
{
public class SampleContext: DbContext
{
public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}
}
My controller
SampleContext dbContext = new SampleContext();
var customerList = dbContext.Customers.ToList();
return View(customerList);
Here is the error
An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
Please help me to solve this problem
Looks like you are trying to create database in same file which is used by ASP.NET membership and you don't have SQLEXPRESS installed on your machine (otherwise Entity Framework would create database with YourNamespace.SampleContext name in your SQLEXPRESS database). So, just add another connection string which will point to another database file:
<connectionStrings>
<add name="SampleContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Sample;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Sample.mdf" />
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EFcodefirst-20131213155231;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EFcodefirst-20131213155231.mdf" />
</connectionStrings>
NOTE: If you don't want connection string to have same name as your context class, you can provide connection string name to constructor of base context class:
public class SampleContext: DbContext
{
public SampleContext()
: base("AnotherConnectionStringName")
{
}
public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}
Modify your dbcontext file :
public class SampleContext: DbContext
{
public SampleContext()
: base("DefaultConnection")
{
}
public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}

Get Connection String from Method returning Connection error Object Refrence not Set to the instance of object ??? Asp.net

i am trying to get connection string from method resulting error object reference not set to the instance object my method is,
this method return connection,
namespace InspectionServices.Services
{
public class ConfigManager
{
public static string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["***"].ConnectionString;
}
}
}
and here i am getting connection by calling method mentioned above,
string connectionString = InspectionServices.Services.ConfigManager.GetConnectionString();
hopes for your suggestion
Thanks in Advance
EDITED:
Appconfig,
<connectionStrings>
<add name="Inspection" connectionString="Data Source=***;Database=***;Integrated Security=SSPI; Persist Security Info=false; Trusted_Connection=Yes;" providerName="System.Data.SqlClient"/>
</connectionStrings>
You mush have web.config entries like this
<connectionStrings>
<add name="name" connectionString="***" />
</connectionStrings>
Only then you can use it in your class.
Some useful links
C# Configuration Manager . ConnectionStrings
http://www.connectionstrings.com/Articles/Show/store-connection-string-in-web-config
namespace InspectionServices.Services
{
public class ConfigManager
{
public static string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["Inspection"].ConnectionString;
}
}
}

How to apply IoC in Development db connection string and Production Db connection string settings

Can anyone kindly provide me an example of using IoC (structureMap / Spring.Net) for swapping connection string in Data Access Layer in Development & Production? (In C# if possible)
Thanks
Don't know about Spring.Net but this is how I usually do it in ASP.Net, assuming that you have a DAL that accept a db connection string.
<connectionStrings>
<add name="Development" connectionString="Enlist=false;MultipleActiveResultSets=True;Data Source=MYPC\SQLEXPRESS;Initial Catalog=Development;Integrated Security=True" providerName="System.Data.SqlClient"/>
<add name="Production" connectionString="Enlist=false;MultipleActiveResultSets=True;Data Source=MYPC\SQLEXPRESS;Initial Catalog=Production;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
public class MySession : ISession
{
public MySession(string connectionName)
{
// ...
}
}
ObjectFactory.Initialize(
x =>
{
x.For<ISession>()
.Use<MySession>().Ctor<string>("connectionName").Is("Development");
//.Use<MySession>().Ctor<string>("connectionName").Is("Production");
}
Dude i wouldn't do that if i was you
When you deploy, your connection strings for all your environments will go out to all your environments (security issue)
You are straying from the standard implementation, which means pain in the long run
But if you really needed to, you would probably have to do something like this: (this might not even work)
<db:provider id="PRODDbProvider" provider="SqlServer-2.0" connectionString="whateveritis" />
<db:provider id="DEVDbProvider" provider="SqlServer-2.0" connectionString="whateveritis" />
<object id="genericAdoTemplate" type="CustomAdoTemplate">
<property name="DbProviders">
<dictionary>
<entry key="PROD" value="PRODDbProvider" />
<entry key="DEV" value="DEVDbProvider" />
</dictionary>
</property>
</object>
Then have a custom AdoTemplate
public class CustomAdoTemplate : Spring.Data.Generic.AdoTemplate {
public object DbProviders {
get;
set;
}
public override object DbProvider {
get {
return DbProviders[GetCurrentEnvironmentKey()];
}
}
}

Categories