When I simply run the project, data is get from server no problems, but there's a requirement of connection string to be in code.
According to material on net I did the following, but just cannot solve the error.
Error
The specified store provider cannot be found in the configuration, or is not valid.
domainservice
public class DomainService1 : LinqToEntitiesDomainService<EMPLOYEEEntities>
{
public override void Initialize(DomainServiceContext context)
{
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Provider = "System.Data.EntityClient";
builder.ProviderConnectionString = #"Data Source=A-63A9D4D7E7834\THIRD;Initial Catalog=EMPLOYEE;Integrated Security=True;";
builder.Metadata = string.Format(#"res://*/{0}.csdl|
res://*/{0}.ssdl|
res://*/{0}.msl", "Model1");
this.ObjectContext.Connection.ConnectionString = builder.ConnectionString;
base.Initialize(context);
}
web.config
<connectionStrings>
<add name="EMPLOYEEEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=A-63A9D4D7E7834\THIRD;Initial Catalog=EMPLOYEE;Integrated Security=True;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
</connectionStrings>
The "System.Data.EntityClient" is a combination of many namespaces/libs therefore it is not recognized.
the right way would be,
public IQueryable<Table1> GetTable1()
{
// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
string serverName = #"A-63A9D4D7E7834\THIRD";
string databaseName = "EMPLOYEE";
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder =
new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = true;
sqlBuilder.MultipleActiveResultSets=True;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// <add name="EMPLOYEEEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=A-63A9D4D7E7834\THIRD;Initial Catalog=EMPLOYEE;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/Models.Model1.csdl|
res://*/Models.Model1.ssdl|
res://*/Models.Model1.msl";
Console.WriteLine(entityBuilder.ToString());
// EntityConnection conn = new EntityConnection(entityBuilder.ToString());
/*
using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
Response.Write("this is a web application");
Console.WriteLine("Just testing the connection.");
conn.Close();
}*/
this.ObjectContext.Connection.ConnectionString = entityBuilder.ToString();
// this.ObjectContext.Connection.Open();
// this.ObjectContext.Connection.BeginTransaction();
// this.ObjectContext.Table1.OrderBy(q => q.ID);
IQueryable<Table1> results = this.ObjectContext.Table1.OrderBy(q => q.ID);
// this.ObjectContext.Connection.Close();
return results;
}
Related
Please note (Environment):
Function App: Version 2,
Target Framework: .Net Core 2.1
I am developing a Function App, that will work like Web Api. This Function App will return the data from database tables, also it'll manipulate files in Azure storage(Blob). But I am stuck as I am unable to create ConnectionString from local.settings.json file. Ideally the connection string should be created by default as I followed some tutorials & no where mentioned any extra steps to create default connectionstring value, just need to create it in local.settings.json file.
following is my local.settings.json file content:-
{
"ConnectionStrings": {
"mycs": "data source=servername;initial catalog=dbname;user id=XXXX;password=XXXX;MultipleActiveResultSets=True;"
},
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"mycs": "data source=servername;initial catalog=dbname;user id=XXXX;password=XXXX;MultipleActiveResultSets=True;"
}
}
following is my HttpTrigger file:
namespace my_api
{
public class myDataContext : DbContext
{
public myDataContext() : base(GetConnectionString()) { }
private static string GetConnectionString()
{
const string providerName = "System.Data.SqlClient";
const string metadata = #"res://*/MYDB.csdl|res://*/MYDB.ssdl|res://*/MYDB.msl";
try
{
string connectString = ConfigurationManager.ConnectionStrings["mycs"].ToString();
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(connectString);
// Set the properties for the data source.
//sqlBuilder.IntegratedSecurity = true;
sqlBuilder.MultipleActiveResultSets = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = metadata;
return entityBuilder.ConnectionString;
}
catch { }
var connectionstring = Environment.GetEnvironmentVariable("mycs");
return connectionstring;
}
public DbSet<flowerset> flowersets
{
get;
set;
}
}
}
Following is the code for :
namespace my_api
{
public static class helpService
{
[FunctionName("helpService_get")]
public static async Task> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log, ExecutionContext context)
{
log.LogInformation("C# HTTP trigger function processed a request helpService_get).");
try {
int page = 0;
int pageSize = 20;
myDataContext entity = new myDataContext();
if (page == 0 && pageSize == 0)
{
return entity.helpsets.ToList();
}
if (pageSize <= 0) { pageSize = 20; }
entity.helpsets.OrderByDescending(x => x.id).Skip((page - 1) * pageSize).Take(pageSize).ToList();
}
catch (Exception exx) {
log.LogInformation("Exception changed (helpService_get): "+exx.Message);
}
return null;
}
}//End of Class
}//End of Namespace
I am getting following error on line entity.helpsets.OrderByDescending(x => x.id).Skip((page - 1) * pageSize).Take(pageSize).ToList();:
Unable to determine the provider name for provider factory of type 'System.Data.SqlClient.SqlClientFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.
According to my test, we can use System.Data.SqlClient to connect Azure SQL in Azure function V2.0. For example
Create an Azure Function with Visual Studio 2019
Install System.Data.SqlClient package(the version I sue is 4.5.1)
Develop the function
local.settings.json file content
"ConnectionStrings": {
"mycs": "Data Source="";Initial Catalog=DotNetAppSqlDb20190826105048_db;User Id="";Password="" "
},
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
Code
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
try
{
var connectionstring = System.Environment.GetEnvironmentVariable($"ConnectionStrings:mycs"); ;
using (SqlConnection connection = new SqlConnection(connectionstring))
{
connection.Open();
log.LogInformation(" sql login success");
StringBuilder sb = new StringBuilder();
sb.Append("select * from dbo.Todoes");
String sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
log.LogInformation("{0} {1}", reader.GetInt32(0), reader.GetString(1));
}
}
}
connection.Close();
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
For more details, please refer to the document
Here's sample code:
private static Raven.Client.Embedded.EmbeddableDocumentStore _documentStore;
public static Raven.Client.Embedded.EmbeddableDocumentStore documentStore
{
get
{
if (_documentStore == null)
{
_documentStore = new Raven.Client.Embedded.EmbeddableDocumentStore
{
DataDirectory = "App_Data/RavenDbData",
UseEmbeddedHttpServer = true
};
_documentStore.Initialize();
}
return _documentStore;
}
}
The exception message looke like this when the _documentStore.Initialize(); line is called:
System.Net.HttpListenerException: The process cannot access the file because it is being used by another process
It turns out that this exception gets thrown if port 8080 is used by anything else. The fix was to add this bit to the web.config to change the port number (pick any port number)
<appSettings>
<add key="Raven/Port" value="8082"/>
</appSettings>
How to form connection between HSQLDB and C# .net ? I have already looked at SharpHSQL and H2Sharp but not able to connect the HSQLDB.
try like this:
Make sure you've already add hsqldb.dll, IKVM.OpenJDK.Core.dll, IKVM.OpenJDK.Jdbc.dll as reference.
If you don't have the IKVM library, you can download here.
At your C#:
using java.sql; //add this.
for create a connection:
private Connection GetConnection()
{
DriverManager.registerDriver(new org.hsqldb.jdbcDriver());
Connection conn = DriverManager.getConnection("jdbc:hsqldb:hsql://[host]/[db name]", "[username]", "[password]");
return conn;
}
how to use it:
public void LoadSetting(String userId)
{
Connection conn = null;
try
{
//Connect it!
conn = GetConnection();
string query = "SELECT A.* FROM table A";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
//Get Query Result
Console.WriteLn(rs.getString("COL1"));
Console.WriteLn(rs.getString("COL2"));
}
}
//Close the Connection
finally
{
if (conn != null && !conn.isClosed())
{
conn.close();
conn = null;
}
}
}
Hope this help.
Cheers...
Basic steps:
Download IKVM.NET and HyperSQL (=HSQLDB) driver.
Convert HSQLDB Java driver to .NET DLL using IKVM.NET to create a hsqldb.dll
Add compile time dependencies to your C# project:
hsqldb.dll
IKVM.OpenJDK.Core.dll
IKVM.OpenJDK.Jdbc.dll
Add runtime dependencies when running your C# program:
IKVM.OpenJDK.Localedata.dll
IKVM.OpenJDK.Text.dll
IKVM.OpenJDK.Util.dll
IKVM.Runtime.dll
Add connection string to your app.config :
<configuration>
<connectionStrings>
<add name="HyperSQL"
connectionString="jdbc:hsqldb:hsql://localhost:9999/xdb;user=SA;password=;" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
C# code:
using System;
using System.Configuration;
namespace HyperSQL
{
class Program
{
readonly static string CONNECTION_STRING = ConfigurationManager.ConnectionStrings["HyperSQL"].ConnectionString;
const string SQL = "SELECT * FROM customer";
static void Main(string[] args)
{
java.sql.DriverManager.registerDriver(new org.hsqldb.jdbcDriver());
using (java.sql.Connection conn = java.sql.DriverManager.getConnection(CONNECTION_STRING))
{
java.sql.PreparedStatement ps = conn.prepareStatement(SQL);
using (java.sql.ResultSet rs = ps.executeQuery())
{
while (rs.next())
{
Console.WriteLine($"ID={rs.getInt("id")}");
Console.WriteLine($"NAME={rs.getString("name")}");
Console.WriteLine($"AGE={rs.getInt("age")}");
Console.WriteLine($"ADDRESS={rs.getString("address")}");
Console.WriteLine($"SALARY={rs.getInt("salary")}");
Console.WriteLine("------------------");
}
}
}
Console.ReadLine();
}
}
}
Here my detailed tutorial how to connect to HyperSQL from C#
var store = new DocumentStore()
{
Url = #"http://localhost"
};
store.Initialize();
Blog blog = new Blog()
{
Title = "Hello RavenDB",
Category = "RavenDB",
Content = "This is a blog about RavenDB",
Comments = new BlogComment[]{
new BlogComment() { Title = "Unrealistic", Content= "This example is unrealistic"},
new BlogComment() { Title = "Nice", Content= "This example is nice"}
}
};
using (IDocumentSession session = store.OpenSession())
{
session.Store(blog);
session.SaveChanges();
}
The above code saves data to the default database. (It is a web application.) But I want it save data to another database that I created the raven management studio (web page). Where do i specify the database name? Also please tell me how I can save the connection string with the database name in the config file. This is how I would save it to config file without the database name
<connectionStrings>
<add name="Local" connectionString="DataDir = ~\Data"/>
<add name="Server" connectionString="Url = http://localhost:8080"/>
</connectionStrings>
All of your questions are explained in the documentation:
new DocumentStore
{
ConnectionStringName = "Local"
}
<connectionStrings>
<add name="Local" connectionString="DataDir=~\Data;Database=MyDatabaseName"/>
<add name="Server" connectionString="Url=http://localhost:8080;Database=MyDatabaseName"/>
</connectionStrings>
The other answers are ok, but for efficiency you really only want one instance of DocumentStore for your application, unless you are running multiple Raven servers and then it would be acceptable to have one per server.
If you are just connecting to different databases on the same server, you should use:
var store = new DocumentStore(...your connection string or inline options...);
using (var session = store.OpenSession("the database name")
{
...
}
You can keep your connection strings data as you shown, best with the databases names at the end:
<connectionStrings>
<add name="Core" connectionString="Url=http://localhost:8082/databases/Core"
providerName="My primary database." />
<add name="Backup" connectionString="Url=http://localhost:8082/databases/Backup"
providerName="My backup stuff." />
</connectionStrings>
Next you can implement singleton class which will keep all your handlers for defined sources, for example:
public class DocumentStoreProvider : IDocumentStoreProvider
{
private static readonly IDictionary<string, IDocumentStore> _documentStores = new Dictionary<string, IDocumentStore>();
private static readonly DocumentStoreProvider _instance = new DocumentStoreProvider();
private DocumentStoreProvider()
{
var connectionStrings = ConfigurationManager.ConnectionStrings;
foreach (ConnectionStringSettings connectionString in connectionStrings)
{
var name = connectionString.Name;
var connection = connectionString.ConnectionString;
IDocumentStore currentStore = new DocumentStore { ConnectionStringName = name };
currentStore.Initialize();
currentStore.DatabaseCommands.EnsureDatabaseExists(name);
IndexCreation.CreateIndexes(Assembly.Load("Your.Assembly.Containing.Indexes"), currentStore);
_documentStores.Add(name, currentStore);
}
}
public static DocumentStoreProvider Instance
{
get { return _instance; }
}
public IDocumentStore GetDocumentStore(string key)
{
return _documentStores[key];
}
}
The usage can be following:
using (var session = DocumentStoreProvider.Instance.GetDocumentStore("Backup").OpenSession())
{
/* do stuff for chosen database... */
session.Store(something);
session.SaveChanges();
}
Here i am uploading Excelsheet which adds data to sql tables.
Code works perfectly on localhost. after hosting it on server its giving me the error,
Access to the path 'D:\INETPUB\VHOSTS\vivek-vichar.org....\temp\excelsheets\Student RegistrationTrial2.xls' is denied.
I have created temp\excelsheets directory already.
protected void import_xls_Click(object sender, EventArgs e)
{
try
{
string savePath;
savePath = Server.MapPath("/temp/excelsheets");
if (xlsupload.HasFile)
{
string fileName = xlsupload.FileName;
savePath = Path.Combine(savePath, fileName);
xlsupload.SaveAs(savePath);
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + savePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet2$]", excelConnection);
OleDbDataReader dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(SqlConnectionstring.mainConnectionString, SqlBulkCopyOptions.KeepIdentity);
if(grouplist.SelectedItem.Text == "A")
{
sqlBulk.DestinationTableName = "dbo.studentA";
}
else if (grouplist.SelectedItem.Text == "B")
{
sqlBulk.DestinationTableName = "dbo.studentB";
}
else if (grouplist.SelectedItem.Text == "C")
{
sqlBulk.DestinationTableName = "dbo.studentC";
}
sqlBulk.ColumnMappings.Add("UserName", "UserName");
sqlBulk.ColumnMappings.Add("Password", "Password");
sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.ColumnMappings.Add("Standard", "Standard");
sqlBulk.ColumnMappings.Add("Division", "Division");
sqlBulk.ColumnMappings.Add("SchoolName", "SchoolName");
sqlBulk.ColumnMappings.Add("Language", "Language");
sqlBulk.WriteToServer(dReader);
lblmsg.Visible = true;
lblmsg.Text = "Your data uploaded successfully";
excelConnection.Close();
}
}
catch (Exception ex)
{
lblmsg.Visible = true;
lblmsg.Text = ex.Message.ToString();
}
Webconfig
<connectionStrings>
<add name="sqlconn" connectionString="Data Source=<servername>;User Id=******;Password=******;persist security info=False;Connect Timeout=0;Max Pool Size=10000" providerName="System.Data.SqlCient" />
On the server, locate the file or folder containing it and :-
Right-click and select Properties.
Add the user account your process is running under to the security permissions with read/write access.
Your connection string here is for your database. The 'user' that needs to access the spreadsheet is the user your IIS application is running as, possibly the IUSR account, or the account that your application pool is configured to use depending on the version of IIS and the setup.