Database error ASP.NET - asp.net-mvc

I have my projects setup as follows (repository pattern):
myProj.Data (Contains the xDB.mdf) [Library]
myProj.Service (Uses myProj.Data) [Library]
myProj.WebApp (Uses myProj.Service) [ASP.NET Website]
In 1. I access my Database via Linq to Sql. The app.config looks like this:
<add name="XDbConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\XDb.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
When I try to retrieve some data via the web, I get this error thrown from the Service Project:
An attempt to attach an auto-named database for file D:\MyProject\XDb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
From this code:
return (from p in repository.GetPostMedia() where p.PostId == postId select p).ToList();

Check in Management Studio that you don't have that database already attached, if so detach it and try again.

I moved the database from the myProj.Data into myProj.Web App_Data folder and it worked.

Related

Howto log to 2 instances of same type of sink (Seq)?

Possible?
Cannot find a "sink forwarder", where one sink can forward to several other sinks, possibly of the same type.
Serilogs documentation (https://github.com/serilog/serilog/wiki/AppSettings)
clearly states that
NOTE: When using serilog: keys need to be unique.*
so adding the same Seq sink several times doesnt seem to be a good idea.
I'm looking for the same concept as in log4net, where one logger can hold several appenders.
Unfortunately the <appSettings> config provider for Serilog doesn't support this case; the appSettings.json one does, if you're able to use it, otherwise configuring the sinks in code WriteTo.Seq(...).WriteTo.Seq(...) is the way to go.
Semi-workaround style of solution:
Put a "read these keys" in appsettigs
Example 1: Read one key
<add key="SerilogToHttpKeys" value="MyMachineA" />
Example 2 (which solves the problem): Read many keys
<add key="SerilogToHttpKeys" value="MyMachineA, MyLocalMachine, MachineOnTheMoon" />
Both cases "points" to an unlimited number of keys, that are then read via code (see 2) and hence be tweaked w/out recompiling
<add key="MyLocalMachine" value="http://localhost:5341/;juzOPqqqqqqqq" />
<add key="MyMachineA" value="http://10.107.14.57:5341/;m8QVnDaqqqqqqqqqqqqq" />
<add key="MachineOnTheMoon" value="http://10.107.14.62:5341/;Ah0tSzqqqqqqqqqqqq"
Loop the keys in code - each key points to a http address with an API key, which is used for logging to Seq, but change the structure of each entry, and you could log to file ect.
foreach (var aKey in System.Configuration.ConfigurationManager.AppSettings.Get("SerilogToHttpKeys")
.Split(',')//Use , as separator
.Select(s => s.Trim()))
{
var fields = System.Configuration.ConfigurationManager.AppSettings.Get(aKey);
var separator = ';';
string serverUrl = fields.Split(separator)[0];
string apiKey = fields.Split(separator)[1];
loggerConfiguration = loggerConfiguration.WriteTo.Seq(serverUrl: serverUrl, apiKey: apiKey);
}
I use this for logging both to my server and my dev machine at the same time - its easier to keep the localhost Seq open when errors occour, and see if I can find them there instead of logging into the server. However, in case my devmachine is not online, I have the logs on the server as well. Off course, if more than one persons accesses the server licenses are needed for Seq, but in a simple "one dev, one dev-machine, one server" it works.

Using connectionstring from app.config with FSharp.Data.SqlClient

I'm using FSharp.Data.SqlClient and trying to move my connectionString from a [<Literal>] to the app.config.
My app.config looks like this
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
</configuration>
And my SqlCommandProvider looks like the below, which should be correct according to http://fsprojects.github.io/FSharp.Data.SqlClient/configuration%20and%20input.html
new SqlCommandProvider<"SELECT ...",
ConnectionStringOrName = "name=DefaultConnection",
SingleRow = true,
AllParametersOptional = true>(??????)
Now the question is. What goes in the last part, the ?????? part.
I tried "name=DefaultConnection" but it gives me a runtime error with name being unsupported.
I can't seem to find any documentation explaining what goes there.
Update
Instaed of fixnig the issue I found this workaround.
https://fsprojects.github.io/FSharp.Configuration/
I don't get the purpose of ConnectionStringOrName if you have to supply the connection string anyway. Also why do you have to specify it twice. Makes very little sense to me :(
When using type providers, you often need two separate data sources:
Compile-time one that is used when you are editing the code and compiling the code. The type provider uses this connection or data source to infer the schema of the data - in case of SQL provider, this is connection to the database that is used to check that all your column names exist etc.
Run-time one is used when you actually run the program after it is deployed somewhere. This is where you'll read the actual data from.
The reason why you need two is that the run-time data source may be determined at runtime and it may not be accessible at compile-time (you typically have access to a dev database, but not to production database). The compile-time connection needs to be a constant, so that the provider can use it (when compiling your code) without running any part of your code.
In case of the SQL command provider:
type SelectCmd = SqlCommandProvider<"SELECT ...",
ConnectionStringOrName = "name=DefaultConnection",
SingleRow = true,
AllParametersOptional = true>
let cmd = new SelectCmd(??????)
"name=DefaultConnection" tells the provider to use an app.config key at compile-time
????? is where you need to specify the run-time connection string
To read the connection string from app.config, you can use the standard .NET methods like using ConfigurationManager:
open System.Configuration
let conn = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
let cmd = new SelectCmd(conn)
Something like this would not work when passing the connection string to the SqlCommandProvider, because this needs to run some code to read the string and that's only possible at runtime. That's why the SQL command provider has a handy option to specify name=DefaultConnection as a special string.

Invalid object name '#Results' SSIS when using sp in dataflow

I have a stored procedure that runs fine in SQL Management Studio but I'm having problems running it in SSIS 2008 R2. If I run it as an Execute SQL Task, it runs fine without any errors but when I use it as an ADO NET Source in a Data Flow Task, I get an error messaging
Invalid object name #Results (Microsoft SQL Server, Error:208)
However when I click Preview, I do get rows of data displayed.
I don't have access rights to modify the stored procedure so I'm not sure what is going on inside the stored procedure itself but as I have said previously, I can run the stored procedure in management studio and when used in an Execute SQL Task in SSIS.
One of the steps in SSIS is validation of metadata - the contract says we should have an integer and then a character size 8. When the data flow database source components (ado or ole) attempt to get their metadata, it's basically boils down the first query that is found.
The approach here is the same hack we use with dynamic tables in stored procedures. Change the stored procedure, which you've specified you cannot do, to provide a hint to SSIS on the expected metadata.
CREATE PROCEDURE dbo.Sample
AS
BEGIN
SET NOCOUNT ON;
-- Any condition that will never evaluate to true
IF NULL = NULL
BEGIN
-- SSIS will key off of this query even
-- though it is impossible for this branch to ever execute
-- So, define our metadata here
SELECT
CAST(NULL AS int) AS MyFirstColumn
, CAST(NULL as char(8)) AS SomeCodeColumn;
END
-- Assume complex queries here that banjax the metadata
-- yet ultimately return the actual data
SELECT TOP 1000
CAST(ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS int) AS MyFirstColumn
, CAST(LEFT(AC.name, 8) AS char(8)) AS SomeCodeColumn
INTO
#RubeG
FROM
sys.all_columns AS AC;
SELECT
RG.MyFirstColumn
, RG.SomeCodeColumn
FROM
#RubeG AS RG;
END
For sources of SQL Server 2012+, you can try to specify the WITH RESULT SETS property to your EXECUTE call.
EXECUTE dbo.Sample
WITH RESULT SETS
(
(
c1 bigint
, c2 varchar(8)
)
);
Biml
Sample biml package definition.
download and install BIDS Helper
Open/create Integration Services project type
Add new biml file
Paste following definition
Adjust connection string value in line 5 (for OLE) an 8 (for ADO.NET)
Ensure the stored procedure dbo.Sample exists
Remove DFT Sample Result Set if using a 2008 database
Code here
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
<Connections>
<Connection
Name="tempdb"
ConnectionString="Data Source=.\dev2014;Initial Catalog=tempdb;Provider=SQLNCLI10.1;Integrated Security=SSPI;"
/>
<AdoNetConnection
Name="CM_ADO"
ConnectionString="Data Source=localhost\dev2014;Integrated Security=SSPI;Connect Timeout=30;Database=tempdb;"
Provider="SQL"
/>
</Connections>
<Packages>
<Package Name="so_31206473">
<Tasks>
<Dataflow Name="DFT Sample">
<Transformations>
<OleDbSource ConnectionName="tempdb" Name="OLESRC dbo_Source">
<DirectInput>EXECUTE dbo.Sample</DirectInput>
</OleDbSource>
<DerivedColumns Name="DER Placeholder" />
</Transformations>
</Dataflow>
<Dataflow Name="DFT Sample RESULTS SET">
<Transformations>
<OleDbSource ConnectionName="tempdb" Name="OLESRC dbo_Source RS">
<DirectInput>
<![CDATA[EXECUTE dbo.Sample
WITH RESULT SETS
(
(
c1 bigint
, c2 varchar(8)
)
);]]>
</DirectInput>
</OleDbSource>
<DerivedColumns Name="DER Placeholder" />
</Transformations>
</Dataflow>
<Dataflow Name="DFT SampleADO">
<Transformations>
<AdoNetSource ConnectionName="CM_ADO" Name="ADOSRC dbo_Sample">
<DirectInput>EXECUTE dbo.Sample</DirectInput>
</AdoNetSource>
<DerivedColumns Name="DER Placeholder" />
</Transformations>
</Dataflow>
<Dataflow Name="DFT SampleADO RESULTS SET">
<Transformations>
<AdoNetSource ConnectionName="CM_ADO" Name="ADOSRC dbo_Sample">
<DirectInput>
<![CDATA[EXECUTE dbo.Sample
WITH RESULT SETS
(
(
c1 bigint
, c2 varchar(8)
)
);]]>
</DirectInput>
</AdoNetSource>
<DerivedColumns Name="DER Placeholder" />
</Transformations>
</Dataflow>
</Tasks>
</Package>
</Packages>
</Biml>
Sample metadata for an OLE Source
WITH RESULTS SET metadata for an OLE Source
The results are the same for ADO.NET providers, I simply didn't notice that nuance to the question when I built my screenshots. Updated Biml makes it trivial to add those in though.

Unit Testing in MVC not creating/accessing database

I have a solution with an MVC project containing a Services project on top of a Core project.
I just added a Unit Tests project and referenced Core and Services - I'm trying to test Services.
I have a basic call in the test:
public class CrudTests
{
private readonly SetServices _setService = new SetServices();
[TestMethod]
public void TestMethod()
{
_setService.CreateSet("Test Set", "Test Set Details", null);
Which ends up failing because the test can't connect to a database. My config has this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\;Initial Catalog=Project.Services.Tests;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Project.Services.Tests.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
I've tried by creating the database Project.Services.Tests and then running, but I get this:
Message=Database 'C:\Program Files\Microsoft SQL
Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\App.Services.Tests.mdf'
already exists. Choose a different database name. Cannot attach the
file
'C:\PROJECTS\App\App\Services.Tests\bin\Debug\Services.Tests.mdf'
as database 'App.Services.Tests'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=65536
Number=1801
Procedure=""
Server=.\
State=2
StackTrace:
I tried deleting the database and letting the test do it's thing, and I get this:
A file activation error occurred. The physical file name
'\Project.Services.Tests.mdf' may be incorrect. Diagnose and correct
additional errors, and retry the operation.
How can I get this working properly?
In Unit Testing you must test the code without any dependency such as database or file system etc.
unit test means testing only that part of code independently.
if you want to test your code by its integration to database you must create Integration Test.
that means you should create an initializing for database usage before running test and a tear down for diposing resources after finishing tests.
maybe this link help you more to understand the difference between Unit Test and Integration Test
you should just fix the connection string and it should work, You are attaching the database file from |DataDirectory| of the test project,

How do I connect to SDF on a Mobile device from desktop application?

C# WinForms .Net 3.5 to SQL CE 3.5 on Mobile 6.1 Device
I'd like to make a connection from a desktop application to a SDF database on my Windows Mobile device while it's connected via ActiveSync. Visual Studio lets me create a Data Connection to my device. The connections tests OK and I can view the data in the database using Visual Studio.
I then create a form and try to fill a DataGridView. When I run the program I get an error that the path to the data base is not valid.
How am I supposed to specify the Mobile device path in the connection string?
In my App.Config, I've tried variations on the path, but none of them work:
connectionString="Data Source=Mobile Device\Program Files\SqlCeViaActiveSync\Orders.sdf"
connectionString="Data Source=\Mobile Device\Program Files\SqlCeViaActiveSync\Orders.sdf"
connectionString="Data Source=Program Files\SqlCeViaActiveSync\Orders.sdf"
connectionString="Data Source=\Program Files\SqlCeViaActiveSync\Orders.sdf"
The full connection string section looks like this:
<connectionStrings>
<add name="SqlCeViaActiveSync.Properties.Settings.OrdersConnectionString"
connectionString="Data Source=Mobile Device\Program Files\SqlCeViaActiveSync\Orders.sdf"
providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
Also, I did make a reference to Microsoft.SqlServerCe.Client, as I found a few articles that mentioned it was necessary.
Can anyone point me to some recent articles/samples or let me know what I'm doing wrong?
Thanks!
I just found that the following works:
SqlCeConnection conn = new SqlCeConnection(#"Data Source='Mobile Device\Program Files\SqlCeViaActiveSync\Orders.sdf';");
conn.Open();
using (SqlCeTransaction trans = conn.BeginTransaction())
{
using (SqlCeCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT [OrderNumber] FROM [Orders];";
trans.Commit();
SqlCeDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
this.listBox1.Items.Add((string)dr["OrderNumber"]);
}
MessageBox.Show(dr.RecordsAffected.ToString());
}
}
conn.Close();
It wasn't exactly what I was looking for but will work for this application.

Resources