Momentarily i am working on an API. I just deployed my API to an online environment. now my problem i came across is the following:
Locally, my API had no problems whatsoever, the problem started when i deployed it.
I debugged my program and this was the problem:
var setups = _context.Setup;
foreach (var setup in setups) //<-- problem
{
if (setup.SetupID == setupItems.SetupID)
{
setup.SetupName = setupItems.SetupName;
counter++; //if it is already in the database
}
}
My new MSSQL database gets stuck on this foreach loop, it returns a 404 error the moment it gets in.
For comparison underneath are the developer as well as the deployment connection string:
Development
Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=***;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False; MultipleActiveResultSets=true
Deployment
Data Source=***;Initial Catalog=***;User ID=***;Password=***;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;MultipleActiveResultSets=true
Question
How do I solve this issue?
UPDATE
The problem is that my online database items are not recognized.
I tried validating my connection string using this method in console:
$conn.ConnectionString = "myConncetionString" # whatever you are testing
$conn.Open()
$conn.Close()
The connection string connected perfectly.
I migrated all the tables in it as well that won't be the problem. for info I am using MSSQL MyLittleAdmin as database. Permissions are not the problem either.
Do you receiving any exception in your code? Please share exact exception you are receiving in your code.
You have two issues here - first: you should materialize the query (_context.Setup.ToList()) otherwise each row is materializing separately what generates a lot of communication between your app and the db. Secund: if your query (collection) will be materialized it is good idea to to stop tracking the changes in the foreach - better is to "search for the changes" just before "Save Changes" to the db
Here is the code, as I would implement it:
var setups = _context.Setup.Where(x => x.SetupID == setupItems.SetupID).ToList();
foreach (var setup in setups)
{
setup.SetupName = setupItems.SetupName;
}
I think I don't know exact context of your code - foreach through all records in the table is not very good idea :) even your exact issue is somewhere else..
Related
I've got a problem resolving my SQLite Database issue.
As the title says, I'm "simply" trying to add some data into a particular table of the database file using SQLite - with the Microsoft.Data.SQLite package.
The code is executed without any errors and even the SQL-Statement execution returns that one row altered. But when I take a look into the db with the db-browser the "inserted" row, simply isn't there at all. This is the code executed:
SqliteConnectionStringBuilder _sqlconsb = new SqliteConnectionStringBuilder();
_sqlconsb.DataSource = _SqliteDatabase;
_sqlconsb.Mode = SqliteOpenMode.ReadWrite;
SqliteConnection _sqlconn = new SqliteConnection(_sqlconsb.ConnectionString);
_sqlconn.Open();
SqliteCommand _sqlcmd = _sqlconn.CreateCommand();
_sqlcmd.CommandText = #"INSERT INTO Mediatypes (Name, Type) VALUES ('Hurrey-1', 'i')";
int _numInsert = _sqlcmd.ExecuteNonQuery();
_sqlconn.Close();
return _numInsert;
I created a complete new WPF-Application with some buttons and executed the same piece of code in that new app. There it also executes without any issues and the data is indeed added to the db file, which I again checked with the db browser.
I've got no idea, with this particular code adds the new row of data in the test app, but does'nt do it's job in my app. I'm also complete lost in further debbuging this issue, because it's executed without any issues.
One more point to consider, I've other methods in my app which are able to add data successfully to the database into other tables. So i think it sholdn't be the database file itself nor the MS.Data.SQLite package in my solution.
I hope there's anyone out there who's able to point me into the right direction to get this debbuged and or solved ...!
I'm trying to test the newly supported transactions in Mongo DB with a simple example I wrote.
I'm using Mongo DB version 4.0.5 with driver version 2.8.1.
It's only a primary instance with no shards/replicas.
I must be missing something basic in the following code.
I create a Mongo client, session & database, then start a transaction, add a document and abort the transaction. After this code, I expect nothing to change in the database, but the document is added. When debugging I can also see the document right after the InsertOne() by using Robo 3T (Mongo client GUI).
Any idea what am I missing?
var client = new MongoClient("mongodb://localhost:27017");
var session = client.StartSession();
var database = session.Client.GetDatabase("myDatabase", new MongoDatabaseSettings
{
GuidRepresentation = GuidRepresentation.Standard,
ReadPreference = ReadPreference.Primary,
WriteConcern = new WriteConcern(1,
new MongoDB.Driver.Optional<TimeSpan?>(TimeSpan.FromSeconds(30))),
});
var entities = database.GetCollection<MyEntity>("test");
session.StartTransaction();
// After this line I can already see the document in the db collection using Mongo client GUI (Robo 3T), although I expect not to see it until committing
entities.InsertOne(new MyEntity { Name = "Entity" });
// This does not have any effect
session.AbortTransaction();
Edit:
It's possible to run MongoDB as a 1-node replica set, although I'm not sure what's the difference between a standalone and a 1-node replica set.
See my post below.
In any case, to use the started transaction the insertion code must receive the session as a parameter:
entities.InsertOne(session, new MyEntity { Name = "Entity" });
With these 2 change now the transaction works.
This is inherently a property of MongoDB itself. (More here and here)
Transactions are only available in a replica set setup
Why isnt it available for standalone instances?
With subdocuments and arrays, document databases (MongoDB) allow related data to be unified hierarchically inside a single data structure. The document can be updated with an atomic operation, giving it the same data integrity guarantees as a multi-table transaction in a relational database.
I found a solution, although not sure what the consequences are, maybe someone can point it out:
It seems it's possible to use Mongo DB as a 1-node replica set (instead of a standalone) by simply adding the following in the mongod.cfg file:
replication:
replSetName: rs1
Also, thanks to the following link the code should use the correct overload of InsertOne() which receives the session as the first parameter (see the edit on the original post):
multiple document transaction not working in c# using mongodb 4.08 community server
I am trying to write data to a FILESTREAM column of an MS SQL database. When running it on the local machine, it works fine, but as soon as connecting to a remote one, it locks up.
Here is what I do (Using NHibernate):
private static readonly string QUERY_GET_PATH =
"select CompressedData.PathName() as path, GET_FILESTREAM_TRANSACTION_CONTEXT() as con from Data.TimeSeries where FS_ID = :dataId";
private static readonly string QUERY_SET_BLANK =
"update Data.TimeSeries set CompressedData = Cast('' as varbinary(max)) where FS_ID = :dataId";
// ...
ISession session = ...
var q1 = session.CreateSQLQuery(QUERY_SET_BLANK);
q1.SetGuid("dataId", ts.DataId);
q1.ExecuteUpdate();
var q2 = session.CreateSQLQuery(QUERY_GET_PATH);
q2.SetGuid("dataId", ts.DataId);
var results = q2.List();
var item = (object[])results[0];
var path = (string)item[0];
var context = (byte[])item[1];
return new SqlFileStream(path, context, FileAccess.Write);
Running this locally works fine, but then I connect to a remote database (this is not in my hands, I just have to write to it) using a connection string like this:
Server=10.0.0.5; Database=TheDatabase; User Id=foo; Password='barfoo';
The returned path looks like:
\\SOME-HOST\SOMEWHERE\v02-A60EC2F8-2B24-11DF-9CC3-AF2E56D89593\Foo\Data\TimeSeries\%!CompressedData\BAD566ED-CD86-42DE-AC71-D13125E89990\VolumeHint-HarddiskVolume1
First I thought it was because of name resolution from 10.0.0.5 to SOME-HOST but it keeps locking up when adding an appropriate entry to my hosts file (ping to the database works).
What might be wrong?
Followup
After waiting for some minutes, I get a Win32Exception with the message The user name or password is incorrect.
I am posting this as an answer so I can mark it as resolved although it is more like a workaround - but I'd like to at least leave an explanation here for others who might face the same or a similar issue.
As I found out, FILESTREAM only works with SSPI, and SSPI in turn only works when the client and server are either in the same domain or when accessing the database locally. This explains why it worked in first place when I accessed the database locally.
Since the database server is in a system set up by a third party working with us, I can't get my client machine into their domain, and I can't get their server into ours. Our workaround is to prepare everything, zip it up, transfer that archive to the database server and have a service running there, locally connected to the database, put everything in. From a security point of view that's okay because both systems only run in a local network with no access to the outside whatsoever.
I'm adding new lines to a database for our company's "order list" for each order created, using the firebird ado.net client. The code i've written works fine for listing items, but inserting new ones doesn't appear elsewhere (e.g. in flamerobin). What I think is happening is that the transaction isn't being committed, seeing as it's recognised within my code (can't add duplicate values).
Code:
using (FbConnection fbCon = new FbConnection)
{
fbCon.Open();
***command w/ parameterised command string***
using (FbTransaction fbTrans = fbCon.BeginTransaction())
using FbCommand orderCommand = new FbCommand(cmdString, fbCon, fbTrans)
{
***Adding parameters and values***
try
{
int recordsAffected = orderCommand.ExecuteNonQuery();
fbTrans.Commit();
}
catch (FbException E)
{
fbTrans.Rollback();
fbCon.Close();
throw E
}
}
recordsAffected returns 1 but I am not able to see the updated values in flamerobin or the db management program. Am i missing something?
If anyone else runs into this problem, it's in Visual Studio's debugging settings. https://visualstudiomagazine.com/blogs/tool-tracker/2012/05/dealing-with-local-databases-or-why-your-updates-dont-stick.aspx explains pretty clearly, but basically VS makes a copy of your database in bin/Debug of your project (Ostensibly to not mess with your data) but if you actually need to use/view the data externally, either link your external application to the debug database (e.g. flamerobin). You may also need to set your project database settings to Copy if Newer if you want your updates to stay, as the default setting copies the database into the folder each time you run your c# app.
I have this odd problem with my records using SQL Server CE in my WPF application. So far I have been successful in storing records on my database. I have a set of settings that I access when opening the application. I'm using LINQPad in order to view my database records.
Here's how I save my database records.
using (var dbc = new MyDbContext())
{
var settings = new UserSetting();
settings.UserId = AppUser.User.Id;
settings.MinimizeKey = minimizeKey;
settings.StartStopKey = startStopKey;
settings.IsStartAtStartUp = isStartAtStartUp ?? false;
settings.IsStoreState = isStoreState ?? false;
dbc.UserSettings.Add(settings);
dbc.SaveChanges();
}
After saving, I view my settings table and I can see that the records are there. My problem is, when I restart my device while the application is currently open. The record seems to be gone. On the other hand, when I close my application before restarting, the records are still there. Obviously restarting the device while the app is still open is not a good practice, but this will happen once in a while and I want my records to still be there.
Any ideas? Thanks!
By default, sql ce has a flush interval of 10 seconds. You can set it to 1 second by adding:
;Flush interval=1
To your connection string
Or you can force immediate flush, as described here: http://erikej.blogspot.dk/2013/05/sql-server-compact-code-snippet-of-week_21.html