I try to run example from https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started but after running next code all tables are cleared. I don't understand why it happens. I expecting that the store var barginBasin = new Store { Name = "Bargin Basin" }; and rows from table StoreProduct with Store_id of this store will be deleted.
using (var session = sessionFactory.OpenSession())
{
session.Delete(session.CreateCriteria(typeof (Store)).List<Store>()[0]);
session.Flush();
}
sessionFactory initialization:
var dbConfig = OracleDataClientConfiguration.Oracle10
.ConnectionString(c => c.FromConnectionStringWithKey("Oracle"))
.Driver<OracleDataClientDriver>()
.ShowSql();
sessionFactory = Fluently.Configure()
.Database(dbConfig)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Employee>())
.BuildSessionFactory();
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="Oracle"
connectionString="DATA SOURCE=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=[IP])(PORT=[PORT]))(CONNECT_DATA=(SERVICE_NAME=XE)));PASSWORD=[PASSWORD];PERSIST SECURITY INFO=True;USER ID=[USER ID]"
providerName="Oracle.DataAccess.Client" />
</connectionStrings>
</configuration>
Related
I have this Q1.config file in my Console Application (.NET 4.5.2)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="globalKey" value="globalValue" />
</appSettings>
<configSections>
<section name="validations" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<validations>
<add key="validationKey" value="validationValue"/>
</validations>
</configuration>
I'm reading it like this
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = "Q1.config" };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
ConfigurationSection validationSettings = config.GetSection("validations");
This works fine:
string globalValue = config.AppSettings.Settings["globalKey"].Value;
But how do I get my "validationKey"? I tried these but they don't work:
validationSettings["validationKey"]
validationSettings.Settings["validationKey"]
(config.GetSection("validations") as NameValueCollection)["validationKey"]
With the answer from #Karthik I ran into an issue... if I use ConfigurationManager.GetSection() I only get null. To get the section I have to use the config object returned by OpenMappedExeConfiguration. However, GetSection() in config isn't of type object as in ConfigurationManager, but DefaultSection from which I can't read the key value pairs, nor can I cast it to NameValueCollection. Browsing on the web I found this article with a solution that worked for me.
Basically extract the XML from the section and parse it manually with an XmlDoc.
public static NameValueCollection GetSectionSettings(string sectionToRead, string configPath)
{
if (!File.Exists(configPath)) { throw new ArgumentException($"File not found: {configPath}", nameof(configPath)); }
var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = configPath };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
string settingsXml = config.GetSection(sectionToRead).SectionInformation.GetRawXml();
XmlDocument settingsXmlDoc = new XmlDocument();
settingsXmlDoc.Load(new StringReader(settingsXml));
NameValueSectionHandler handler = new NameValueSectionHandler();
return handler.Create(null, null, settingsXmlDoc.DocumentElement) as NameValueCollection;
}
Here you go
Your XML configuration
<configuration>
<configSections>
<section name="validations" type="System.Configuration.AppSettingsSection" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="globalKey" value="globalValue" />
</appSettings>
<validations>
<add key="validationKey" value="validationValue"/>
</validations>
</configuration>
And you can get these values in C# using
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = "Q1.config" };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
NameValueCollection validationSettings = (NameValueCollection)ConfigurationManager.GetSection("validations");
string globalValue = validationSettings[0];
I've used an index here validationSettings[0] to access the value. You can use your key to get the value
Thanks
Below is my try to use Memcache in a console application.
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="enyim.com"/>
<section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection,Enyim.Caching"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<enyim.com>
<memcached protocol="Binary">
<severs>
<add address="127.0.0.1" port="11211"/>
</severs>
</memcached>
</enyim.com>
</configuration>
C#
static void Main(string[] args)
{
DateTime dt = DateTime.Now;
try
{
using (MemcachedClient memcache = new MemcachedClient())
{
string cachedTime = memcache.Get<string>("CachedTime");
if (cachedTime == null)
{
memcache.Store(Enyim.Caching.Memcached.StoreMode.Set, "CachedTime", DateTime.Now.ToString());
cachedTime = memcache.Get<string>("CachedTime");
}
Console.WriteLine(cachedTime);
Console.WriteLine(dt);
}
}
catch (Exception ex)
{
}
}
Every time the value of cachedDate is NULL
Change App.Config to the following and it should work:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="enyim.com">
<section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<enyim.com>
<memcached>
<servers>
<add address="127.0.0.1" port="11211" />
</servers>
<socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" />
</memcached>
</enyim.com>
</configuration>
I am trying to create a Database with entity framework code-first environment.
The tables in database are identity tables.
The problem is with SQL server's database creation. There is no database created When I ran application.
However, I am able to find physical find here at this location -
C:\Users\user\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS\HWAPI.mdf
So whenever I do add any table or change the structure then all the changes are happening in above location and think that this is not using master database.
There is no database created in my local SQL server.
Have a look at my code -
StartUp.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
config.DependencyResolver = new NinjectResolver(NinjectWebCommon.CreateKernel());
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
app.CreatePerOwinContext(OwinAuthDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new AuthorizationServerProvider()
};
}
}
And there is the context -
public class OwinAuthDbContext : IdentityDbContext<ApplicationUser>, IDisposable
{
public OwinAuthDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Database.SetInitializer<OwinAuthDbContext>(null);
}
public static OwinAuthDbContext Create()
{
return new OwinAuthDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");
modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");
modelBuilder.Entity<IdentityUserLogin>().ToTable("AspNetUserLogins");
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
web.config
<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>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HWAPI;Integrated Security=SSPI;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Please assist and let me know if additional info is required.
Your problem is with the connection string.You need to try as shown below.
If you need to use Localhost then :
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=localhost; Database=HWAPI;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
If you need to use LocalDb then :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\HWAPI.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Thanks everybody for putting their inputs.
It turns out that I needed to setup credentials for existing database. After I setup credentials security for database then it worked.
before -
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HWAPI;Integrated Security=SSPI;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
after -
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HWAPI;User ID=sa;Password=truw#123" providerName="System.Data.SqlClient"/>
This solved my issue and I was able to connect to database within SQLEXPRESS.
I am tried to add some data into the database but it not adding inside the database table ,But it didnt show any exception also.I dont know whats the problem
try
{
SqlConnection con = new SqlConnection(#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Store(Item,Description,Expences) values('pen','blue','10')", con);
cmd.ExecuteNonQuery();
con.Close();
}
My App Config file
[![<?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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="StoreContext" connectionString="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" /></connectionStrings>
</configuration>][1]][1]
My Table
CREATE TABLE [dbo].[Store] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Item] VARCHAR (20) NOT NULL,
[Description] VARCHAR (100) NULL,
[Expences] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
You have an error in your request, Expences is a integer :
SqlCommand cmd = new SqlCommand("insert into Store(Item,Description,Expences) values('pen','blue',10)", con);
Try below code, below code is written without using any tool so please try to adjust the code.
try
{
DbContext xyz = new DbContext();
Store oStore = new Store();
oStore.Item = "pen";
oStore.Description = "blue";
oStore.Expences = 10;
xyz.Stores.Add(oStore);
xyz.SaveChanges(); // never forgot to do SaveChanges
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
I'm a quite beginner with config sections in c#
I want to create a custom section in config file. What I've tried after googling is as the follows
Config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="MyCustomSections">
<section name="CustomSection" type="CustomSectionTest.CustomSection,CustomSection"/>
</sectionGroup>
</configSections>
<MyCustomSections>
<CustomSection key="Default"/>
</MyCustomSections>
</configuration>
CustomSection.cs
namespace CustomSectionTest
{
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("key", DefaultValue="Default", IsRequired = true)]
[StringValidator(InvalidCharacters = "~!##$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
public String Key
{
get { return this["key"].ToString(); }
set { this["key"] = value; }
}
}
}
When I use this code to retrieve Section I get an error saying configuration error.
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("CustomSection");
What am I missing?
Thanks.
Edit
What I need ultimately is
<CustomConfigSettings>
<Setting id="1">
<add key="Name" value="N"/>
<add key="Type" value="D"/>
</Setting>
<Setting id="2">
<add key="Name" value="O"/>
<add key="Type" value="E"/>
</Setting>
<Setting id="3">
<add key="Name" value="P"/>
<add key="Type" value="F"/>
</Setting>
</CustomConfigSettings>
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="customAppSettingsGroup">
<section name="customAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</sectionGroup>
</configSections>
<customAppSettingsGroup>
<customAppSettings>
<add key="KeyOne" value="ValueOne"/>
<add key="KeyTwo" value="ValueTwo"/>
</customAppSettings>
</customAppSettingsGroup>
</configuration>
Usage:
NameValueCollection settings =
ConfigurationManager.GetSection("customAppSettingsGroup/customAppSettings")
as System.Collections.Specialized.NameValueCollection;
if (settings != null)
{
foreach (string key in settings.AllKeys)
{
Response.Write(key + ": " + settings[key] + "<br />");
}
}
Try using:
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("MyCustomSections/CustomSection");
You need both the name of the section group and the custom section.
Highlight ConfigurationSection press F1,
You will see that the implementation on the MSDN website overrides a property called "Properties" which returns a "ConfigurationPropertyCollection", as your properties have a matching attribute of that type you should be able to populate this collection with your properties if not wrap them in the same way the MS guys have.