Issue with LinqToDb T4 templates for a SqlLite database (using LoadSQLiteMetadata) - sqlite

I'm trying to use a local SqlLite database (in my app_data) folder with LinqToDb.
Anybody an idea why LinqToDb cannot work with the following connectionstring ?
<connectionStrings>
<add name="RecyclesDB"
providerName="System.Data.SqlLite"
connectionString="data source=|DataDirectory|Recycles.sqlite3;Version=3;"
/>
</connectionStrings>
I can perfectly use this connectionstring to retrieve data the old-school way.
SQLiteConnection sqlConn;
var sqlCmd = new SQLiteCommand();
using (sqlConn = new SQLiteConnection(ConfigurationManager.ConnectionStrings["RecyclesDB"].ConnectionString))
{
sqlConn.Open();
sqlCmd.Connection = sqlConn;
/* .... */
}
However, when I try to use LinqToDB with the following t4 template it fails
<## template language="C#" debug="True" hostSpecific="True" #>
<## output extension=".generated.cs" #>
<## include file="$(ProjectDir)LinqToDB.Templates\LinqToDB.SQLite.Tools.ttinclude" #>
<## include file="$(ProjectDir)LinqToDB.Templates\PluralizationService.ttinclude" #>
<#
NamespaceName = "RecycleDashboard";
LoadSQLiteMetadata(LoadSQLiteMetadata(#"C:\inetpub\RecycleDashboard\app_data", "Recycles.sqlite3"););
GenerateModel();
#>
To specify the issue. The T4 template generates the models alright, but when I try to use these with the following code I get a null reference
using (var db = new RecyclesDB())
{
var recycles =
(from recycle in db.AppRecycles
select recycle).ToList();
}
The exception on new RecyclesDB() is :
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=linq2db
StackTrace:
at LinqToDB.Data.DataConnection..ctor(String configurationString) in i:\linq2db\Source\Data\DataConnection.cs:line 41
at LinqToDB.Data.DataConnection..ctor() in i:\linq2db\Source\Data\DataConnection.cs:line 24
at RecycleDashboard.RecyclesDB..ctor() in
...
Anybody an idea what's wrong here ?

OK, just in case anyone else stumbles over issues with the Sqlite Dataprovider too
I resolved this but specifying my DataConnection specifically as follows
(GetDataProvider and GetConnection as suggested on https://github.com/linq2db/linq2db):
public partial class RecyclesDB : LinqToDB.Data.DataConnection
{
public RecyclesDB() : base(GetDataProvider(), GetConnection()) { }
private static IDataProvider GetDataProvider()
{
return new LinqToDB.DataProvider.SQLite.SQLiteDataProvider();
}
private static IDbConnection GetConnection()
{
return new SQLiteConnection(ConfigurationManager.ConnectionStrings["RecyclesDB"].ConnectionString);
}
}
Not sure why the code generated by the T4 template fails, but it looked like the LinqToDB DataConnection class couldn't resolve the dataprovidername 'System.Data.SQLite' automatically.

Related

EPPlus: Exception when attempting to use SaveAs method: Can't load type System.Security.Crytopgraphy.Pkcs.SignedCms

I'm attempting to save a successfully loaded excel file as an .xlsm file and I'm getting the following error:
{System.InvalidOperationException: Error saving file C:\VS\ExcelManager\ExcelManager\File.xlsm ---> System.TypeLoadException: Could not load type 'System.Security.Cryptography.Pkcs.SignedCms' from assembly 'System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
at OfficeOpenXml.VBA.ExcelVbaSignature.GetSignature()
at OfficeOpenXml.VBA.ExcelVbaSignature..ctor(ZipPackagePart vbaPart)
at OfficeOpenXml.VBA.ExcelVbaProject.get_Signature()
at OfficeOpenXml.VBA.ExcelVbaProject.Save()
at OfficeOpenXml.ExcelWorkbook.Save()
at OfficeOpenXml.ExcelPackage.Save()
--- End of inner exception stack trace ---
at OfficeOpenXml.ExcelPackage.Save()
at OfficeOpenXml.ExcelPackage.SaveAs(FileInfo file)
at ExcelManager.Controllers.ExcelController.PrepareExcelFile() in C:\VS\ExcelManager\ExcelManager\Controllers\ExcelController.cs:line 71
at ExcelManager.Controllers.ExcelController.Get() in C:\VS\ExcelManager\ExcelManager\Controllers\ExcelController.cs:line 80
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()}
}
Here's the code using EPPlus in .NET Core 2.0.:
{namespace ExcelManager.Controllers
{
[Route("api/excel")]
public class ExcelController : Controller
{
//private const string XlsxContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
private const string XlsxContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
private void PrepareExcelFile()
{
//https://github.com/JanKallman/EPPlus/issues/31
//Otherwise, I get an EPP error
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
ExcelPackage pck = new ExcelPackage(new System.IO.FileInfo("File.xlsx"));
pck.Workbook.CreateVBAProject();
var sb = new StringBuilder();
//Add VBA Code here
pck.Workbook.CodeModule.Code = sb.ToString();
//Save as XLSM
pck.SaveAs(new System.IO.FileInfo("File.xlsm"));}
I also tried the EPPlus.CORE nuget package and received a "Not Supported Exception". I'm not trying to encrypt or do anything special with the file other than add VBA code and I have no problems opening and saving the file manually.
Any ideas would be greatly appreciated.
Your question lacks some information, like what version of EPPlus are you using?
Anyway, I did the following:
Created a .Net Core 2.0 ASP.net core MVC project.
Installed EPPLus prerelease v4.5.0.1-beta (which supports .net core 2.0) and tried the following code:
ExcelPackage pck = new ExcelPackage(new System.IO.FileInfo("d:\\a.xlsx"));
var sb = new StringBuilder();
//Add VBA Code here
sb =new StringBuilder( "valid VB code");
pck.Workbook.CreateVBAProject();
pck.Workbook.CodeModule.Code = sb.ToString();
//Save as XLSM
pck.SaveAs(new System.IO.FileInfo("D:\\a.xlsm"));
And it works perfectly.
Please make sure that you are using the right EPPlus version.

can't connect to sql 2012 in asp.net , c# due to app.config , settings.designer.cs not regenerating

i cant connect to sql 2012 in asp.net , c#
file: defalut.aspx -> page_Load
List<ozhatdata.tbl_diller> diller_result;
using (var ctx = new ozhatdata.bagDataContext())
{
diller_result = ozhatdata.DilIslemleri.GetAllLanguages(ctx);
}
int cnt = diller_result.Count ; // diller_result is null error
when i go to definition (F12) of the bagDataContext()
file: bag.designer.cs
public bagDataContext() :
base(global::ozhatdata.Properties.Settings.Default.ozhatprojeConnectionString15, mappingSource)
{
OnCreated();
}
when i go to definition (F12) of ozhatprojeConnectionString15
file: settings.designer.cs
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute( "Data Source=.\\SQLEXPRESS;Initial Catalog=ozhatproje;Persist Security Info=True;"+
"User ID=sa;Password=123; ")]
public string ozhatprojeConnectionString15 {
get {
return ((string)(this["ozhatprojeConnectionString15"]));
}
}
later i learned there is app.config file this line was present in app.config
<add name="Settings.ozhatprojeConnectionString15"
connectionString="Data Source=LIVE2RISE\SQLEXPRESS;Initial Catalog=ozhatproje;Persist Security Info=True;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
i can connect to "user:sa pass:123" on "ms sql management studio"
!!!!error!!!!!!
System.NullReferenceException: Object reference not set to an instance of an object.
diller_result.count // this diller_result is null in debugger
line 36: for (int i = 0; i < diller_result.Count; i++)
Kaynak Dosya: c:\inetpub\wwwroot\site\Default.aspx.cs line : 36
im trying to figure out since yesterday.
please help me, thnks.
edit: after responce i tracked adn put a breakpoint
public static List<tbl_diller> GetAllLanguages(bagDataContext ctx = null)
{
try
{
//some stuf was here i deleted
}
catch (Exception ex)
{
string ms = ex.Message; // !!breakpoint
// the exception= coundt find stored procedure "dbo.getalllangs"
return null;
}
}
thank you. the problem is solved. it was caused by an evil try-cath duo.
i'll be more cautious with these "try catchs" from now on.
2nd time and Solution: this time eventhough i edit app.config, program uses old ConString from settings.designer.cs(i tracked it while debugging).
the program uses connString from setting.designer.cs too. app.config is not used/looked up/referred when Debugging
so we have to navigate in the solution>properties>settings.designer.cs edit connectionStrings there too.
i hope this helps anyone in future.
you can read this too:
Force regeneration of Settings.settings file after change in app.config
It seems that it is the call to ozhatdata.DilIslemleri.GetAllLanguagesthat did return a null value for diller_result.
You might want to check in that method what is causing it to return null.

Changing dataset connection string in web config at runtime

I have a c# generated dataset.
How can I change the connection string so I can use the dataset with another (identically structured yet differently populated) database?
This has to occur at runtime as I do not know the server or database name at compile time. I am using c# 3.5.
I think there is no simple way and you cannot change the Connection-String programmatically for the entire DataSet since it's defined for every TableAdapter.
You need to create the partial class of the TableAdapter to change the connection-string since the Connection property is internal (if your DAL is in a different assembly). Don't change the designer.cs file since it will be recreated automatically after the next change on the designer. To create it just right-click the DataSet and chose "show code".
For example (assuming the TableAdapter is named ProductTableAdapter):
namespace WindowsFormsApplication1.DataSet1TableAdapters
{
public partial class ProductTableAdapter
{
public string ConnectionString {
get { return Connection.ConnectionString; }
set { Connection.ConnectionString = value; }
}
}
}
Now you can change it easily:
var productTableAdapter = new DataSet1TableAdapters.ProductTableAdapter();
productTableAdapter.ConnectionString = someOtherConnectionString;
Here's a screenshot of my sample DataSet and the created file DataSet1.cs:
ide mvs 2008
in your settings.designer.cs verifier or edit this
public string NamOfappConnectionString{
get {
return ((string)(this["NamOfappConnectionString"]));
}
//add this line
set {
this["NamOfappConnectionString"]=value;
}
}
//atr untime use this
string myconnexion = "Data Source=" + txt_data_source.Text + ";Initial Catalog=" + txt_initial_catalog.Text + ";Persist Security Info=True;";
ConfigurationManager.AppSettings.Set("NamOfappConnectionString", myconnexion);
//save into setting
Properties.Settings.Default.NamOfappConnectionString= myconnexion;
Application.Restart();

SqlException when creating a new item in Asp.Net MVC 3 app

In my "web store" mvc app I want to add items to database. Items table has CreatedBy field and it is a foreign key from User table UserId field. Everything was working before I put the database into the App_Data folder. Now I get the SqlException when trying to create a new Item:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Item_contains_User". The conflict occurred in database "C:\USERS\ALEKSEY\REPOS\2\WEBSTORE\WEBSTORE\APP_DATA\WEBSTORE.MDF", table "dbo.Users", column 'UserId'.
Here is the Create method of ItemRepository class:
public Item CreateItem(int productId, Guid userId)
{
var item = new Item
{
ProductId = productId,
CreatedBy = userId,
};
_dataContext.Items.InsertOnSubmit(item);
_dataContext.SubmitChanges(); // in this line the exception occures !
return item;
}
Here is the controller method Create:
[HttpGet]
public ViewResult Create()
{
var p = _productRepository.CreateProduct("", "", 0, "", "", "");
var userId = (Guid)Membership.GetUser().ProviderUserKey;
var item = _itemsRepository.CreateItem(p.ProductId, userId);
// some code
return View(model);
}
Besides, I use Linq to Sql model drag an' drop approach.
Here is the changed web.config connection string part:
<connectionStrings>
<add name="WebStoreConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\WebStore.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
As I said everything was working before I moved the database to App_Data file. I also tried to remove the dependency between Items and Users tables - the exact same exception.
Any help would be appropriate. Thanks in advance!
Edits:
Ok, now I really broke the dependency between Items and Users tables and no exception occures. But! I have to somehow know who has created each product, so breaking the dependency is not an option. I also tried to remove all code that initializes the CreatedBy field.
Any ideas??
Edits (part 2):
The second comment below gives a great advise! I found that all users that are created are stored now in the aspnet.sdf database!!!
But if I remove the connection string "DeafaultConnection":
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
I will get ConfigurationErrorsException:
"The connection name 'DefaultConnection' was not found in the applications
configuration or the connection string is empty."
in the folowing line:
var userId = (Guid)Membership.GetUser().ProviderUserKey;
Ok, as I guessed the issue was in the configuration. Each provider (for some reason) in the connection string had "DefaultConnection". I changed it to "WebStoreConnectionString". And now everything works!
p.s. thanks #w0lf, he pushed the thoughts in the right direction)

subsonic 3.0.0.3 multiple database connection failover

am using MVC and Subsonic 3.0.0.3 but i cant seem to pin down a specific point for multiple database connection.
normally in normal .net i would have my 2 strings in the web.config file
and have a database class for my project, within this db class i would do something like this:
try
{
conn.ConnectionString = server1;
conn.Open();
}
catch (MySqlException)
{
conn.ConnectionString = server2;
conn.Open();
}
I am trying to pin down the one place in subsonic's created files where something like this would be best to place and maybe an up to date example on how to achieve it. I have googled etc but the examples shown are for an older subsonic.
many thanks
If you look in Context.tt at line 35 you'll see the following code:
public <#=DatabaseName#>DB()
{
DataProvider = ProviderFactory.GetProvider("<#=ConnectionStringName#>");
Init();
}
This is where the provider is getting setup for you so if you add a BackupConnectionStringName variable in Settings.ttinclude after the ConnectionStringName at line 20 then you should be able to check your connection is working and user your fallback if not. For example:
public <#=DatabaseName#>DB()
{
DataProvider = ProviderFactory.GetProvider("<#=ConnectionStringName#>");
Init();
try
{
DataProvider.CreateConnection();
}
catch(SqlException)
{
DataProvider = ProviderFactory.GetProvider("<#=BackupConnectionStringName#>");
Init();
}
}
NB You may need to do some clean up to make sure a connection is not left open by CreateConnection.

Resources