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.
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.
I am using a web application where user pass one argument to the service and it will return string datatype which is query result. In the service i am using Entity Framework to query based on the user input but i am unable to get the data instead throwing an exception in my webapplication saying.....
The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
Webapplication and service are two different solutions.
Code in My WCF service
public string GetFunctionality(string UserId)
{
string strRoleName = string.Empty;
objEntity = new SYMPHONY_TVEntities();
var Function = from t1 in objEntity.Users join t2 in objEntity.User_Role on t1.Role equals t2.User_Role1 where t1.UserID == UserId select t2;
var UserName = from it in objEntity.Users where it.UserID == UserId select it;
//Here i am getting exception
User_Role objRole = Function.First();
User objUser = UserName.First();
if (objRole.User_Function != null && objUser.User_Name != null)
{
strRoleName = objRole.User_Function + "$" + objUser.User_Name;
}
return strRoleName;
}
My connection string WCF service
<add name="SYMPHONY_TVEntities" connectionString="metadata=res://*/UsersModel.csdl|res://*/UsersModel.ssdl|res://*/UsersModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=inhi1u-hd0212\;Initial Catalog="SYMPHONY TV";Integrated Security=True;MultipleActiveResultSets=True'" providerName="System.Data.EntityClient" /></connectionStrings>
You code looks ok. The exception says it is unable to connect to the db. This means your connection string might be wrong, please verify your connection string. If this fails try adding this line of code after your objEntity. (Why?)
objEntity = new SYMPHONY_TVEntities();
objEntity.Connection.Open();
I am trying to query against the table storage but I am getting the following error:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error
xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<code>InvalidInput</code>
<message xml:lang="en-US">One of the request inputs is not
valid.</message>
</error>
The code I use is as follows:
public IEnumerable<ShoppingItemEntity> Get(string shoppingRowKey) {
var ctx = getTableServiceContext();
var shoppingItems = ctx.CreateQuery<ShoppingItemEntity>(
Constants.TABLE_STORAGE_SHOPPING_ITEM_TABLE_NAME
).Where(x => x.PartitionKey == string.Empty && x.ShoppingId == shoppingRowKey).AsTableServiceQuery();
return shoppingItems.ToList();
}
private TableServiceContext getTableServiceContext() {
var account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["DataConnectionString"]);
return account.CreateCloudTableClient().GetDataServiceContext();
}
The strange thing here is that if I run the query without where clause, I get no errors:
public IEnumerable<ShoppingItemEntity> Get(string shoppingRowKey) {
var ctx = getTableServiceContext();
var shoppingItems = ctx.CreateQuery<ShoppingItemEntity>(
Constants.TABLE_STORAGE_SHOPPING_ITEM_TABLE_NAME
).AsTableServiceQuery();
return shoppingItems.ToList();
}
What do u think is the problem here?
There are articles here and here shows the similar experience you have had with Azure Table storage. When dealing with Azure Development Storage you really need to “convince” the table service provider that you know what you are doing by inserting some dummy entities.
I believe you sure like this article Azure Table Storage, what a pain in the ass.
I have an auction site, not like ebay (as the most think).
Now my problem is follow: On the startpage are a lot of auctions displayed (ASP.NET). All Auction (let's say min. 10, max 50) have a timer. Now I must have a look nearly every second for each auction (filter is not started and not ended) if the timer is reseted (what happens when someone bid).
So I will have a query with a lot of amount back every second, must update 10-50 Textboxes every second and that for every user that visit the page.
Any ideas who solve it performance-good?
You don't have to query SQL every second to change the second counters in your textboxes. You should use Javascript to automatically adjust the seconds left from the start time.
The start time should only get changed when the start time in the SQL tables has been reset. You can use AJAX to update the Textboxes.
You do not have to query SQL once a second to tell when your timers have been reset. You should use a SQL cache dependency. Basically, a SQL Dependency tells you when when it's data has changed, instead of you having to ask SQL every second if anything has changed.
The workflow is as follows:
Make initial SQL query, with a SQL Dependency object, specifying a "callback" method
Cache the result
Return the cached result to your pages until the SQL data has changed
When the SQL data has changed, the SQL Dependency calls the "callback" method you defined
Callback method clears your SQL cache, and re-queries SQL
Repeat steps 2 - 6.
It's a little complicated if you're not used to working with Delegates and dependencies, but it's well worth the time spent because it eliminates repetitive querying.
Sql Cache Dependency Example C# ASP.Net 2.0
In your Global.aspx page, add this code:
<script runat="server">
string mySqlConnection = "<<Enter your connection string here.>>";
void Application_Start(object sender, EventArgs e)
{
// Start subscribing to SQL Server 2005 Notification Services.
System.Data.SqlClient.SqlDependency.Start(mySqlConnection);
}
void Application_End(object sender, EventArgs e)
{
// Stop subscribing to SQL Server 2005 Notification Services.
System.Data.SqlClient.SqlDependency.Stop(mySqlConnection);
}
</script>
In your Default.aspx page, add this code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblCacheDisplay" runat="server" />
<br />
<asp:Label ID="lblWasQueryExecuted" runat="server" />
</div>
</form>
</body>
</html>
The Default.aspx page will display your data, and will say whether the data came from the Application Cache, or from SQL.
In your Default.aspx.cs page, add this code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
private static SqlDependency sqlDependency;
private static bool cacheIsValid = false; // cacheIsValid is set to "false" when the SQL data is changed.
private static string mySqlConnection = "<<Enter you connection string here. It MUST use a different user than the Global.aspx connection string.>>";
protected void Page_Load(object sender, EventArgs e)
{
string myCachedData = (string)HttpContext.Current.Cache.Get("myCachedData");
if (myCachedData == null || !cacheIsValid) // Remember that cached objects can be removed from the cache at any time by the garbage collector, you cannot assume that they exist!
{
myCachedData = GetMyDataFromSql();
cacheIsValid = true;
lblWasQueryExecuted.Text = "SQL was queried for this data.";
}
else
{
lblWasQueryExecuted.Text = "This data came from the Application-level cache. It should be deleted if the SQL data changes.";
}
lblCacheDisplay.Text = myCachedData;
}
public static string GetMyDataFromSql()
{
string returnSqlData = String.Empty;
string storedProcedureName = "<<Enter you stored procedure name here.>>";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcedureName;
cmd.Connection = new SqlConnection(mySqlConnection);
cmd.Connection.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
returnSqlData = sdr.GetString(1);
}
// Only one Sql dependency needs to be created per application start. Since each Sql dependency keeps a connection
// to the Sql database open at all times, we want to make sure we have only one Sql dependency at any given time.
if (!cacheIsValid)
{
HttpContext.Current.Cache.Remove("myCachedData");
}
object hasSqlDependency = HttpContext.Current.Cache.Get("myCachedData");
if (hasSqlDependency == null)
{
CreateSqlDependency();
HttpContext.Current.Cache.Add("myCachedData", returnSqlData, null, DateTime.MaxValue,
TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
}
cmd.Connection.Close();
return returnSqlData;
}
public static void SqlDependency_OnChange(Object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
// The Sql data has changed, so the current cache is out-dated. Therefore, mark it as being invalid.
cacheIsValid = false; // We do not have access to HttpContext.Current right now, so we cannot clear the cache ourselves right now. Instead, we have to mark it as being invalid, and let other code update it.
// Recreate the Sql dependency, since it disappears after sqlDependency_OnChange is called. This will keep the
// connection to the Sql database open, so we can continue to be notified if the SQL data changes.
CreateSqlDependency();
}
}
private static void CreateSqlDependency()
{
SqlConnection sqlConn = new SqlConnection(mySqlConnection);
sqlConn.Open();
// If any tables in this query are modified (data changes, table definition changes, etc.), SqlDependency_OnChange will be called.
SqlCommand cmdDependency = new SqlCommand("<<SELECT column FROM myTable>>", sqlConn);
sqlDependency = new SqlDependency(cmdDependency);
sqlDependency.OnChange += new OnChangeEventHandler(SqlDependency_OnChange);
// Even though we don't do anything with the results of this query, it still needs to be executed in order to set the Sql dependency.
// If you comment out this code, the Sql dependency will not be properly created, and SqlDependency_OnChange will never be notified of
// changes to the SQL data.
SqlDataReader objReader = cmdDependency.ExecuteReader();
objReader.Close();
sqlConn.Close();
}
}
Make the appropriate changes marked by the "<<" and ">>", and you should be good to go.
Note that the two SQL user accounts must have very specific SQL 2005 permissions. Here's how you can setup the SQL user permissions.
All of the timers on the page should automatically decrement one tick every second (if it is below the "display seconds" threshold - otherwise update minute once a minute). This is handled through client-side javascript using a timer to trigger the updates.
Whenever an auction's time is reset (due to a bid) this is updated in the db, and also in a server-side cache. The cache is stores the time reset, the auctionID and the new end-time for the auction
Once every second or so, the page sends an Ajax request (JSON, preferably) back to the server, asking for all of the auctionIDs and new end-times for all auctions whose time has been reset since the last time this page requested it (a value that is stored on the client-side at every request). Based on the return value, only the updated auctions are updated on the client side. And the DB is only queried on the initial page load - all subsequent update requests hit the cache.
All you need to get it which textbox has been reset, the rest can use a gui timer.
so you need to make a reset log table and put a row each time someone reset (put a bid).
now - each sec you select * from log where lognumber > LAST_NUMBER_THAT_YOUR SCREEN_ALREADY_GOT
you get the list of only changed items.
I think it might do the work most efficient...
just make sure to delete old records from this log table....