Why is my azure process not connecting to azure database? - c#

I have a web app and a batch pool.
In the batch pool, created tasks are using the same database as the web app.
Today I started receiving the following exception in the batch:
A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
The code base has not changed, older versions do not work, there were no updates, it just popped out of the blue. I repeated a couple tasks in a controlled debug environment in VS and they went through without any exceptions thrown. I went in and added the batch node’s IP to the sql server firewall rules, also no result. Meanwhile, the web application uses the database just fine.
Both the web app and batch pool are located in East US.
Here’s a snippet from Program.cs in my batch task:
MyEntities db; //MyEntities extends DbContext
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder connstr = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder();
connstr.ProviderConnectionString = connectionString;
connstr.Provider = "System.Data.SqlClient";
connstr.Metadata = "res://*/MyEntities.csdl|res://*/MyEntities.ssdl|res://*/MyEntities.msl";
try {
db = new PepeEntities(connstr.ConnectionString);
}
The connection string looks like this:
Persist Security Info=True; Data Source=<host>; Initial Catalog=<database name>; Integrated Security=False; User ID=<login>; Password=<password>; MultipleActiveResultSets=True; Connect Timeout=30; Encrypt=True;
Edit:
This problem has subsided the same way it appeared: out of the blue. I’ll carry out tests whenever it surfaces again.

You can try one of these 2 possibilities:
1. Enabling an Execution Strategy:
public class MyEntitiesConfiguration : DbConfiguration
{
public MyEntitiesConfiguration()
{
SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());
}
}
# please view more details here:https://msdn.microsoft.com/en-US/data/dn456835
2. if you have explicitly opened the connection, ensure that you close it. You can use an using statement:
using(var db = new PepeEntities(connstr.ConnectionString){
..do your work
}
https://blogs.msdn.microsoft.com/appfabriccat/2010/12/10/sql-azure-and-entity-framework-connection-fault-handling/

Related

How to use Two SqlConnection in single TransactionScope in asp.net c#

I have installed sql server 2008 R2 in two systems, from this one system act as a server and another is client.
I need to copy product from server system database to client system database
In my web.config
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=SERVER-PC\SQLEXPRESS2008;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
<add name="DBConnection1" connectionString="Data Source=CLIENT-PC\SQLEXPRESS2008;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=1;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
Here My Coding
using (TransactionScope trnsScope = new TransactionScope())
{
try
{
List<Master_ProductBLL> lstProduct = new List<Master_ProductBLL>();
//My First SQL Connection For Server
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
{
connection.Open();
//Here I can get All Products from Server Database
lstProduct = Master_ProductBLL.GetMaster_ProductBLLs(DBAction.Status.Active, "");
connection.Dispose();
}
//My Second SQL Connection For Client
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection1"].ConnectionString))
{
connection.Open();
//Here I have save my Server Product into Client SQL Server
foreach (Master_ProductBLL item in lstProduct)
{
item.Save(true);
}
connection.Dispose();
}
trnsScope.Complete();
trnsScope.Dispose();
}
catch (TransactionException ex)
{
trnsScope.Dispose();
throw ex;
}
}
It shows an Error like
MSDTC on server 'CLIENT-PC\SQLEXPRESS2008' is unavailable
Unable to get the address of the distributed transaction coordinator for the server, from the server. Is DTC enabled on the server?
I have google it and find the following details
go to Services. (START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES)
Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.
make this service to run Automatically for solving this issue permanently
I have done the above steps both server and client.
But Still have an error
I think for two (or more) SQL servers to be transactionnaly 'synced', you have to configure network DTC as MSDTC service is in charge of a lot of stuff about transactions... (your client should use the server's one).
To do this :
type dcomcnfg in run...
open Component services | Computers
Right click "Local Computer" and go to MSDTC tab
uncheck Use a local coordinator and type in your server name (or IP)
make sure you followed the steps mentionned in
MSDTC on server 'server is unavailable
on both the client and the server.
Not really sure it'll work, but pretty sure it won't if you don't do that.
Which database you want to use create object of that database.it is simple
SqlConnection connection1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString();
SqlConnection connection1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection1"].ConnectionString

Working with MongoLab from .NET - permissions problems

I've open an account on MongoLab (free sandbox account for testing). I have code that's running on my local MongoDb server and running just fine without any problems.
In MongoLab I've created a database and created a user for that database and placed the connection string they gave me in my application:
mongodb://<dbuser>:<dbpassword>#<my_id>.mlab.com:52408/<my_db>
I even tried this:
mongodb://<dbuser>:<dbpassword>#<my_id>.mlab.com:52408/<my_db>?authMode=scram-sha1&rm.tcpNoDelay=true
In my .NET code I'm connecting to my database:
MongoClient client = new MongoClient(MY_CONNECTION_STRING);
IMongoDatabase database = client.GetDatabase("MyTestDb");
_versionRulesCollection = database.GetCollection<VersionRule>("VersionRules");
_versionDetailsCollection = database.GetCollection<VersionDetails>("VersionDetails");
but when I try to do something like this:
_versionDetailsCollection.Indexes.CreateOneAsync(Builders<VersionDetails>.IndexKeys.Ascending(x => x.ProductName).Ascending(y => y.DeviceType).Ascending(z => z.VersionName))
I get an exception saying
System.AggregateException: One or more errors occurred. ---> MongoDB.Driver.MongoCommandException: Command createIndexes failed: not authorized on MyTestDb to execute command { createIndexes: "VersionDetails", indexes: [ { key: { ProductName: 1, DeviceType: 1, VersionName: 1 }, name: "ProductName_1_DeviceType_1_VersionName_1" } ] }
Even trying to do a query I got:
not authorized for query on MyTestDb .VersionDetails
I don't see any way to set permission for users on the portal. The database is created dynamically in my app. And I'm at a lost here.
What am I doing wrong (it works on my local machine)?

"Timeout while getting a connection from pool." Hangfire.Postgres

I'm new to Hangfire, so probably I'm messing up somewhere. I have the Hangfire configured like in: https://github.com/HangfireIO/Hangfire#installation
but instead of:
config.UseSqlServerStorage("<connection string or its name>");
I have:
config.UsePostgreSqlStorage("Server=127.0.0.1;Port=5432;User Id=postgres;Password=pwd;Database=Hangfire");
So I created an Hangfire Database in my DB.
And then, I'm building and running my project. It is ok. Creating all tables in Hangfire DB at my postgres. It is working great.
But then, when I'm trying:
BackgroundJob.Enqueue(() => HubService.SendPushNotificationToUsers(threadParticipants, messageApi.SenderId, messageApi.SenderName, messageApi.ThreadId, messageApi.Content));
I'm receiving an exception with the InnerMessage:
"Timeout while getting a connection from pool." postgres
Am I missing something?
Try to turn off Connection Pool via ConnectionString or String Builder.
Here is how we do it
var sb = new NpgsqlConnectionStringBuilder(connectionString);
sb.Pooling = false;
app.UseHangfire(config =>
{
config.UseActivator(new WindsorJobActivator(container.Kernel));
config.UsePostgreSqlStorage(sb.ToString(), new PostgreSqlStorageOptions() { UseNativeDatabaseTransactions = true });
config.UseServer();
});
Did you try to reduce the amount of HangFire workers instead?
Maybe these are consuming your connection pool as Hangfire uses by default 20 workers * X connections each (don't remember how many but they are several) and that could be consuming your connection pool... therefore the connection timeout...
You can set how many workers you want to use in the hangfire initialization.
In this example you would use only 1 worker...
app.UseHangfire(config =>
{
config.UseServer(1);
});

Entity framework connection string enable to connect to DB server

I'm using the entity framework in a winforms application.
When i set scsb.DataSource ="localhost" every thing works fine but when i try to connect to onother DB server i got an exception:
"The underlying provider failed on Open."
public DistributionSSEntities1 Connection()
{
var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "192.168.1.100";
scsb.InitialCatalog = "DistributionSS";
scsb.IntegratedSecurity = true;
//------------------------
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata ="res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = scsb.ConnectionString;
DistributionSSEntities1 db = new DistributionSSEntities1(builder.ToString());
return db;
}
Has the remote Sql been setup to allow remote connections? Has the remote Sql been allowed access through the windows firewall... there's so many reasons why it wouldn't connect.
You're using Integrated Security - which may work great for a local Sql; but the network user that your WinForm app is running under must have the correct rights to access the remote box.
I'd suggest to start eliminating possibilities do the following:
Check the Sql logs on the target server. That always has the exact reason why an attemp failed - not the watered down version you get through the exception. (eg. C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\Log)
Connect to it using a sql username password - not integrated security to make sure it's not that
Firewall
EDIT
It's important to remember that the error messages return to the client regarding login attempt failures are purposefully obscure or without information - to limit an attacker gaining enough information to improve the attack (see the technet article for proof). So checking the Sql Server logs is a necessity - if your login/connection attempt actually made it to the server.
From Article:
To increase security, the error message that is returned to the client
deliberately hides the nature of the authentication error. However, in
the SQL Server error log, a corresponding error contains an error
state that maps to an authentication failure condition. Compare the
error state to the following list to determine the reason for the
login failure.
public DistributionSSEntities Connection()
{
string ConString = "SERVER=192.168.1.100;DATABASE=DistributionSS;UID=sa;PASSWORD=125;";
SqlConnectionStringBuilder SCB= new SqlConnectionStringBuilder(ConString);
//------------------------
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata = "res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = SCB.ConnectionString;
DistributionSSEntities db = new DistributionSSEntities(builder.ToString());
return db;
}

System Data Entity. The underlying provider failed on Open

I am creating 2 projects that have the same database (it's an MDF database). The first one is the map editor, and I use XNA 4 and Web Services to connect to it. The second one is the game itself and uses XNA 3.1 and Entity Data Model to connect database.
When I run the map editor and access the database, it runs properly. Bbut when I run the game and access the database, it shows an error "The underlying provider failed on Open"
I think the connection from the web service is not closed yet. But I don't know where I should close the connection.
Here is my code from the web service:
public Map AddNewMap(string username, string mapName, int sizeX, int sizeY)
{
using (BaseModelDataContext context = new BaseModelDataContext())
{
Map newMap = new Map()
{
Username = username,
Name = mapName,
SizeX = sizeX,
SizeY = sizeY,
Upload_Date = DateTime.Now,
Status = 0
};
context.Maps.InsertOnSubmit(newMap);
context.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);
context.Dispose();
return newMap;
}
}
EDIT:
Here is the entity data model code :
using (MazeEntities ent = new MazeEntities())
{
ent.Connection.Open();
return (from map in ent.Map
select map).ToList<Map>();
}
This code runs properly if I did not use the web service before. If I use the web service first, it shows an error at ent.Connection.Open();
Here is the inner exception:
Cannot open user default database. Login failed.\r\nLogin failed for user 'erkape-PC\erkape'.
Connection string for web service :
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\3DMapDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Connection string for the game:
"metadata=res:///MazeDataModel.csdl|res:///MazeDataModel.ssdl|res://*/MazeDataModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\eRKaPe\DropBox\TA\Program\3D_Map_Editor\3DMapEditorServices\App_Data\3DMapDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
For a quick check, can you try adding the following line after the using:
using (BaseModelDataContext context = new BaseModelDataContext())
{
context.Connection.Open();
OR
context.Database.Connection.Open();
// your code here
Finally I found a way to solve my problem after reading some articles.
The connection from the web service doesn't close automatically after I close the map editor. That is why I can't access my database from the game.
I have to change the connection string from both application, I set the User Instance to False. The game can access the database this way.
Please check the following post
http://th2tran.blogspot.ae/2009/06/underlying-provider-failed-on-open.html
Also please Enable for 32 Bit application in the APplication Pool of that application.
This may resolve.
You are trying to return an object (Map) which is associated with the Context. This object has the context information which can't be returned to the client.
You will need to create your own DataContract (a type having necessary properties) that you want to expose to the client.
Or you can use the POCO implementation As described here

Categories